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 |
---|---|---|---|---|---|---|
./partial_match/1/0x3fc5923C3bcF3bE6008d24b1232e373924bD7889/sources/Emiswap.sol | called once by the factory at time of deployment | function initialize(IERC20[] calldata assets) external {
require(assets.length == 2, "Emiswap: only 2 tokens allowed");
tokens = assets;
for (uint256 i = 0; i < assets.length; i++) {
require(!isToken[assets[i]], "Emiswap: duplicate tokens");
isToken[assets[i]] = true;
}
}
| 3,942,728 | [
1,
11777,
3647,
635,
326,
3272,
622,
813,
434,
6314,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
12,
45,
654,
39,
3462,
8526,
745,
892,
7176,
13,
3903,
288,
203,
3639,
2583,
12,
9971,
18,
2469,
422,
576,
16,
315,
1514,
291,
91,
438,
30,
1338,
576,
2430,
2935,
8863,
203,
203,
3639,
2430,
273,
7176,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
7176,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2583,
12,
5,
291,
1345,
63,
9971,
63,
77,
65,
6487,
315,
1514,
291,
91,
438,
30,
6751,
2430,
8863,
203,
5411,
353,
1345,
63,
9971,
63,
77,
13563,
273,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IERC20 {
function TOTALSUPPLY622() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF753(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER955(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL691(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER876(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFER955.selector, to, value));
}
function SAFETRANSFERFROM621(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFERFROM690.selector, from, to, value));
}
function SAFEAPPROVE2(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE76(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, value));
}
function SAFEINCREASEALLOWANCE52(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE76(address(this), spender).ADD393(value);
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE76(address(this), spender).SUB829(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN191(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. 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).FUNCTIONCALL585(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");
}
}
}
interface IWETH {
function DEPOSIT379() external payable; //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW91(uint) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Router01 {
function FACTORY423() external pure returns (address); //inject NONSTANDARD NAMING
function WETH656() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY566( //inject NONSTANDARD NAMING
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 ADDLIQUIDITYETH439( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY294( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH142( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT785( //inject NONSTANDARD NAMING
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 REMOVELIQUIDITYETHWITHPERMIT822( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENS694( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS112( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS23(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH134(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH465(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS477(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE151(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT667(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN118(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT962(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN769(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS84( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS171( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS513( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS617( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS347( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT816(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN577(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP591( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC313(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY897() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY423() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0588() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1553() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES947() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST382() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST280() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST968() external view returns (uint); //inject NONSTANDARD NAMING
function MINT750(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN945(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP412(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM546(address to) external; //inject NONSTANDARD NAMING
function SYNC14() external; //inject NONSTANDARD NAMING
function INITIALIZE840(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED444(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO98() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER656() external view returns (address); //inject NONSTANDARD NAMING
function MIGRATOR786() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR761(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS341(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH448() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR119(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO526(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER51(address) external; //inject NONSTANDARD NAMING
function SETMIGRATOR114(address) external; //inject NONSTANDARD NAMING
}
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_entered266 = 1; //inject NONSTANDARD NAMING
uint256 private constant _entered280 = 2; //inject NONSTANDARD NAMING
uint256 private _status;
constructor () internal {
_status = _not_entered266;
}
modifier NONREENTRANT384() { //inject NONSTANDARD NAMING
// On the first call to nonReentrant, _notEntered will be true
require(_status != _entered280, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _entered280;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _not_entered266;
}
}
library Math {
function MAX80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN629(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE241(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
library Address {
function ISCONTRACT204(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE55(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 FUNCTIONCALL585(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL585(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL585(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE394(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE130(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE130(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 _FUNCTIONCALLWITHVALUE394(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE394(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT204(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);
}
}
}
}
library SafeMath {
function ADD393(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB829(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB829(a, b, "SafeMath: subtraction overflow");
}
function SUB829(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 MUL131(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 DIV283(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV283(a, b, "SafeMath: division by zero");
}
function DIV283(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 MOD208(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD208(a, b, "SafeMath: modulo by zero");
}
function MOD208(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library MathUtils {
using SafeMath for uint256;
function SQRT196(uint256 x) internal pure returns (uint256 y) { //inject NONSTANDARD NAMING
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function ROUNDEDDIV172(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, 'div by 0');
uint256 halfB = (b.MOD208(2) == 0) ? (b.DIV283(2)) : (b.DIV283(2).ADD393(1));
return (a.MOD208(b) >= halfB) ? (a.DIV283(b).ADD393(1)) : (a.DIV283(b));
}
}
interface IUniswapV2ERC20 {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Callee {
function UNISWAPV2CALL695(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING
}
interface IERC20Uniswap {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external view returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
}
abstract contract Context {
function _MSGSENDER27() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA543() 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;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME590() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL603() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS715() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY622() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF753(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER955(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER21(_MSGSENDER27(), recipient, amount);
return true;
}
function ALLOWANCE76(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE213(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, amount);
return true;
}
function TRANSFERFROM690(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER21(sender, recipient, amount);
_APPROVE77(sender, _MSGSENDER27(), _allowances[sender][_MSGSENDER27()].SUB829(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE203(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].ADD393(addedValue));
return true;
}
function DECREASEALLOWANCE568(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].SUB829(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER21(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER156(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB829(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD393(amount);
emit TRANSFER649(sender, recipient, amount);
}
function _MINT693(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER156(address(0), account, amount);
_totalSupply = _totalSupply.ADD393(amount);
_balances[account] = _balances[account].ADD393(amount);
emit TRANSFER649(address(0), account, amount);
}
function _BURN313(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER156(account, address(0), amount);
_balances[account] = _balances[account].SUB829(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB829(amount);
emit TRANSFER649(account, address(0), amount);
}
function _APPROVE77(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 APPROVAL691(owner, spender, amount);
}
function _SETUPDECIMALS749(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER156(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event APPROVAL691(address indexed src, address indexed guy, uint wad); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed src, address indexed dst, uint wad); //inject NONSTANDARD NAMING
event DEPOSIT981(address indexed dst, uint wad); //inject NONSTANDARD NAMING
event WITHDRAWAL378(address indexed src, uint wad); //inject NONSTANDARD NAMING
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
receive() external payable {
DEPOSIT379();
}
function DEPOSIT379() public payable { //inject NONSTANDARD NAMING
balanceOf[msg.sender] += msg.value;
DEPOSIT981(msg.sender, msg.value);
}
function WITHDRAW91(uint wad) public { //inject NONSTANDARD NAMING
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
WITHDRAWAL378(msg.sender, wad);
}
function TOTALSUPPLY622() public view returns (uint) { //inject NONSTANDARD NAMING
return address(this).balance;
}
function APPROVE213(address guy, uint wad) public returns (bool) { //inject NONSTANDARD NAMING
allowance[msg.sender][guy] = wad;
APPROVAL691(msg.sender, guy, wad);
return true;
}
function TRANSFER955(address dst, uint wad) public returns (bool) { //inject NONSTANDARD NAMING
return TRANSFERFROM690(msg.sender, dst, wad);
}
function TRANSFERFROM690(address src, address dst, uint wad) //inject NONSTANDARD NAMING
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(- 1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
TRANSFER649(src, dst, wad);
return true;
}
}
contract twis is ERC20 {
address minter;
modifier ONLYMINTER285 { //inject NONSTANDARD NAMING
require(msg.sender == minter, 'Only minter can call this function.');
_;
}
constructor(address _minter) public ERC20('Twister', 'TWIS') {
minter = _minter;
}
function MINT750(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING
_MINT693(account, amount);
}
function BURN945(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING
_BURN313(account, amount);
}
}
contract Twister is ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for IERC20;
event STAKED534(address indexed from, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING
event WITHDRAWN851(address indexed to, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING
event CLAIMED515(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
event HALVING833(uint256 amount); //inject NONSTANDARD NAMING
event RECEIVED501(address indexed from, uint256 amount); //inject NONSTANDARD NAMING
twis public token;
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
address public weth;
address payable public treasury;
address public pairAddress;
struct AccountInfo {
// Staked LP token balance
uint256 balance;
uint256 peakBalance;
uint256 withdrawTimestamp;
uint256 reward;
uint256 rewardPerTokenPaid;
}
mapping(address => AccountInfo) public accountInfos;
// Staked LP token total supply
uint256 private _totalSupply = 0;
uint256 public constant halving_duration255 = 7 days; //inject NONSTANDARD NAMING
uint256 public rewardAllocation = 1500 * 1e18;
uint256 public halvingTimestamp = 0;
uint256 public lastUpdateTimestamp = 0;
uint256 public rewardRate = 0;
uint256 public rewardPerTokenStored = 0;
// Farming will be open on this timestamp
// Date and time (GMT): Monday, October 26, 2020 3:00:00 PM
uint256 public farmingStartTimestamp = 1604635200;
bool public farmingStarted = false;
// Max 10% / day LP withdraw
uint256 public constant withdraw_limit638 = 10; //inject NONSTANDARD NAMING
// Burn address
address constant burn_address389 = 0x000000000000000000000000000000000000dEaD; //inject NONSTANDARD NAMING
// Dev decided to launch without whitelist but since it has been coded and tested, so dev will leave it here.
// Whitelisted address
mapping (address => bool) public whitelists;
// Whitelist deposited balance
mapping (address => uint256) public whitelistBalance;
// End period for whitelist advantage
uint256 public whitelistEndTimestamp = 0;
// Max stake for whitelist
uint256 public constant whitelist_stake_limit67 = 3 ether; //inject NONSTANDARD NAMING
// Whitelist advantage duration (reduced to 1 minutes since we dont have whitelist)
uint256 public constant whitelist_duration869 = 1 minutes; //inject NONSTANDARD NAMING
constructor(address _routerAddress, address[] memory _whitelists) public {
token = new twis(address(this));
router = IUniswapV2Router02(_routerAddress);
factory = IUniswapV2Factory(router.FACTORY423());
weth = router.WETH656();
treasury = msg.sender;
pairAddress = factory.CREATEPAIR119(address(token), weth);
// Calc reward rate
rewardRate = rewardAllocation.DIV283(halving_duration255);
// Init whitelist
_SETUPWHITELISTS161(_whitelists);
whitelistEndTimestamp = farmingStartTimestamp.ADD393(whitelist_duration869);
}
receive() external payable {
emit RECEIVED501(msg.sender, msg.value);
}
function STAKE961() external payable NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
require(msg.value > 0, 'Cannot stake 0');
require(!address(msg.sender).ISCONTRACT204(), 'Please use your individual account');
// If we are still in whitelist duration
if (whitelistEndTimestamp >= block.timestamp) {
require(whitelists[msg.sender], 'Only whitelisted address can stake right now');
whitelistBalance[msg.sender] = whitelistBalance[msg.sender].ADD393(msg.value);
require(whitelistBalance[msg.sender] <= whitelist_stake_limit67, 'Cannot stake more than allowed in whitelist period');
}
// 10% compensation fee
// since dev doesn't hold any initial supply
uint256 fee = msg.value.DIV283(10);
uint256 amount = msg.value.SUB829(fee);
treasury.transfer(fee);
uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress);
uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress);
// If eth amount = 0 then set initial price to 1 eth = 2 twis
uint256 amountTokenDesired = ethAmount == 0 ? (amount * 2) : amount.MUL131(tokenAmount).DIV283(ethAmount);
// Mint borrowed twis
token.MINT750(address(this), amountTokenDesired);
// Add liquidity in uniswap
uint256 amountETHDesired = amount;
IERC20(token).APPROVE213(address(router), amountTokenDesired);
(,, uint256 liquidity) = router.ADDLIQUIDITYETH439{value : amountETHDesired}(address(token), amountTokenDesired, 1, 1, address(this), block.timestamp + 1 days);
// Add LP token to total supply
_totalSupply = _totalSupply.ADD393(liquidity);
// Add to balance
accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.ADD393(liquidity);
// Set peak balance
if (accountInfos[msg.sender].balance > accountInfos[msg.sender].peakBalance) {
accountInfos[msg.sender].peakBalance = accountInfos[msg.sender].balance;
}
// Set stake timestamp as withdraw timestamp
// to prevent withdraw immediately after first staking
if (accountInfos[msg.sender].withdrawTimestamp == 0) {
accountInfos[msg.sender].withdrawTimestamp = block.timestamp;
}
emit STAKED534(msg.sender, msg.value, liquidity);
}
function WITHDRAW91() external NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
require(accountInfos[msg.sender].withdrawTimestamp + 1 days <= block.timestamp, 'You must wait 1 day since your last withdraw or stake');
require(accountInfos[msg.sender].balance > 0, 'Cannot withdraw 0');
// Limit withdraw LP token
uint256 amount = accountInfos[msg.sender].peakBalance.DIV283(withdraw_limit638);
if (accountInfos[msg.sender].balance < amount) {
amount = accountInfos[msg.sender].balance;
}
// Reduce total supply
_totalSupply = _totalSupply.SUB829(amount);
// Reduce balance
accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.SUB829(amount);
// Set timestamp
accountInfos[msg.sender].withdrawTimestamp = block.timestamp;
// Remove liquidity in uniswap
IERC20(pairAddress).APPROVE213(address(router), amount);
(uint256 tokenAmount, uint256 ethAmount) = router.REMOVELIQUIDITY294(address(token), weth, amount, 0, 0, address(this), block.timestamp + 1 days);
// Burn borrowed twis
token.BURN945(address(this), tokenAmount);
// Withdraw ETH and send to sender
IWETH(weth).WITHDRAW91(ethAmount);
msg.sender.transfer(ethAmount);
emit WITHDRAWN851(msg.sender, ethAmount, amount);
}
function CLAIM763() external NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
uint256 reward = accountInfos[msg.sender].reward;
require(reward > 0, 'There is no reward to claim');
if (reward > 0) {
// Reduce first
accountInfos[msg.sender].reward = 0;
// Apply tax
uint256 taxDenominator = CLAIMTAXDENOMINATOR467();
uint256 tax = taxDenominator > 0 ? reward.DIV283(taxDenominator) : 0;
uint256 net = reward.SUB829(tax);
// Send reward
token.MINT750(msg.sender, net);
if (tax > 0) {
// Burn taxed token
token.MINT750(burn_address389, tax);
}
emit CLAIMED515(msg.sender, reward);
}
}
function TOTALSUPPLY622() external view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF753(address account) external view returns (uint256) { //inject NONSTANDARD NAMING
return accountInfos[account].balance;
}
function BURNEDTOKENAMOUNT890() public view returns (uint256) { //inject NONSTANDARD NAMING
return token.BALANCEOF753(burn_address389);
}
function REWARDPERTOKEN638() public view returns (uint256) { //inject NONSTANDARD NAMING
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored
.ADD393(
LASTREWARDTIMESTAMP705()
.SUB829(lastUpdateTimestamp)
.MUL131(rewardRate)
.MUL131(1e18)
.DIV283(_totalSupply)
);
}
function LASTREWARDTIMESTAMP705() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN629(block.timestamp, halvingTimestamp);
}
function REWARDEARNED380(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return accountInfos[account].balance.MUL131(
REWARDPERTOKEN638().SUB829(accountInfos[account].rewardPerTokenPaid)
)
.DIV283(1e18)
.ADD393(accountInfos[account].reward);
}
// Token price in eth
function TOKENPRICE205() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress);
uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress);
return tokenAmount > 0 ?
// Current price
ethAmount.MUL131(1e18).DIV283(tokenAmount) :
// Initial price
(uint256(1e18).DIV283(2));
}
function CLAIMTAXDENOMINATOR467() public view returns (uint256) { //inject NONSTANDARD NAMING
if (block.timestamp < farmingStartTimestamp + 1 days) {
return 4;
} else if (block.timestamp < farmingStartTimestamp + 2 days) {
return 5;
} else if (block.timestamp < farmingStartTimestamp + 3 days) {
return 10;
} else if (block.timestamp < farmingStartTimestamp + 4 days) {
return 20;
} else {
return 0;
}
}
function _UPDATEREWARD485(address account) internal { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN638();
lastUpdateTimestamp = LASTREWARDTIMESTAMP705();
if (account != address(0)) {
accountInfos[account].reward = REWARDEARNED380(account);
accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored;
}
}
// Do halving when timestamp reached
function _HALVING349() internal { //inject NONSTANDARD NAMING
if (block.timestamp >= halvingTimestamp) {
rewardAllocation = rewardAllocation.DIV283(2);
rewardRate = rewardAllocation.DIV283(halving_duration255);
halvingTimestamp = halvingTimestamp.ADD393(halving_duration255);
_UPDATEREWARD485(msg.sender);
emit HALVING833(rewardAllocation);
}
}
// Check if farming is started
function _CHECKFARMING62() internal { //inject NONSTANDARD NAMING
require(farmingStartTimestamp <= block.timestamp, 'Please wait until farming started');
if (!farmingStarted) {
farmingStarted = true;
halvingTimestamp = block.timestamp.ADD393(halving_duration255);
lastUpdateTimestamp = block.timestamp;
}
}
function _SETUPWHITELISTS161(address[] memory addresses) internal { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < addresses.length; i++) {
whitelists[addresses[i]] = true;
}
}
} | inject NONSTANDARD NAMING
| function DOMAIN_SEPARATOR647() external view returns (bytes32); | 12,607,364 | [
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,
27025,
67,
4550,
30792,
1435,
3903,
1476,
1135,
261,
3890,
1578,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x2ec627c6412EC5267CA2Ec27C72E6e93D4b44784/sources/contracts/HealthRecord.sol | function to add doctor to record | function addDoctorToRecord(uint256 _recordId, uint256 _doctorId)
public
returns (bool)
{
Record storage record = records[_recordId];
record.doctors.push(_doctorId);
return true;
}
| 1,926,896 | [
1,
915,
358,
527,
741,
30206,
358,
1409,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
527,
3244,
30206,
774,
2115,
12,
11890,
5034,
389,
3366,
548,
16,
2254,
5034,
389,
2896,
30206,
548,
13,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
5059,
2502,
1409,
273,
3853,
63,
67,
3366,
548,
15533,
203,
3639,
1409,
18,
2896,
299,
1383,
18,
6206,
24899,
2896,
30206,
548,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x81c7a9d494c74F113cCa32d174925352bD3875f1/sources/_connext/nxtp-contracts/contracts/nomad-core/contracts/Replica.sol | * @notice Emitted when the value for optimisticTimeout is set @param timeout The new value for optimistic timeout/ | event SetOptimisticTimeout(uint256 timeout);
| 1,910,475 | [
1,
1514,
11541,
1347,
326,
460,
364,
5213,
5846,
2694,
353,
444,
225,
2021,
1021,
394,
460,
364,
5213,
5846,
2021,
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,
225,
871,
1000,
13930,
5846,
2694,
12,
11890,
5034,
2021,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.6;
import "../interfaces/ILinkdropCommon.sol";
import "../storage/LinkdropStorage.sol";
import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol";
contract LinkdropCommon is ILinkdropCommon, LinkdropStorage {
/**
* @dev Function called only once to set owner, linkdrop master, contract version and chain id
* @param _owner Owner address
* @param _linkdropMaster Address corresponding to master key
* @param _version Contract version
* @param _chainId Network id
*/
function initialize
(
address _owner,
address payable _linkdropMaster,
uint _version,
uint _chainId
)
public
returns (bool)
{
require(!_initialized, "Already initialized");
owner = _owner;
linkdropMaster = _linkdropMaster;
isLinkdropSigner[linkdropMaster] = true;
version = _version;
chainId = _chainId;
_initialized = true;
return true;
}
modifier onlyLinkdropMaster() {
require(msg.sender == linkdropMaster, "Only linkdrop master");
_;
}
modifier whenNotPaused() {
require(!paused(), "Paused");
_;
}
/**
* @dev Indicates whether a link is claimed or not
* @param _linkId Address corresponding to link key
* @return True if claimed
*/
function isClaimedLink(address _linkId) public view returns (bool) {
return claimedTo[_linkId] != address(0);
}
/**
* @dev Indicates whether a link is canceled or not
* @param _linkId Address corresponding to link key
* @return True if canceled
*/
function isCanceledLink(address _linkId) public view returns (bool) {
return _canceled[_linkId];
}
/**
* @dev Indicates whether a contract is paused or not
* @return True if paused
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Function to cancel a link, can only be called by linkdrop master
* @param _linkId Address corresponding to link key
* @return True if success
*/
function cancel(address _linkId) external onlyLinkdropMaster returns (bool) {
require(!isClaimedLink(_linkId), "Claimed link");
_canceled[_linkId] = true;
emit Canceled(_linkId, now);
return true;
}
/**
* @dev Function to withdraw eth to linkdrop master, can only be called by linkdrop master
* @return True if success
*/
function withdraw() external onlyLinkdropMaster returns (bool) {
linkdropMaster.transfer(address(this).balance);
return true;
}
/**
* @dev Function to pause contract, can only be called by linkdrop master
* @return True if success
*/
function pause() external onlyLinkdropMaster whenNotPaused returns (bool) {
_paused = true;
emit Paused(now);
return true;
}
/**
* @dev Function to unpause contract, can only be called by linkdrop master
* @return True if success
*/
function unpause() external onlyLinkdropMaster returns (bool) {
require(paused(), "Unpaused");
_paused = false;
emit Unpaused(now);
return true;
}
/**
* @dev Function to add new signing key, can only be called by linkdrop master
* @param _linkdropSigner Address corresponding to signing key
* @return True if success
*/
function addSigner(address _linkdropSigner) external onlyLinkdropMaster returns (bool) {
require(_linkdropSigner != address(0), "Invalid address");
isLinkdropSigner[_linkdropSigner] = true;
return true;
}
/**
* @dev Function to remove signing key, can only be called by linkdrop master
* @param _linkdropSigner Address corresponding to signing key
* @return True if success
*/
function removeSigner(address _linkdropSigner) external onlyLinkdropMaster returns (bool) {
require(_linkdropSigner != address(0), "Invalid address");
isLinkdropSigner[_linkdropSigner] = false;
return true;
}
/**
* @dev Function to destroy this contract, can only be called by owner (factory) or linkdrop master
* Withdraws all the remaining ETH to linkdrop master
*/
function destroy() external {
require (msg.sender == owner || msg.sender == linkdropMaster, "Only owner or linkdrop master");
selfdestruct(linkdropMaster);
}
/**
* @dev Function for other contracts to be able to fetch the mastercopy version
* @return Master copy version
*/
function getMasterCopyVersion() external view returns (uint) {
return version;
}
/**
* @dev Fallback function to accept ETH
*/
function () external payable {}
} | * @dev Function to pause contract, can only be called by linkdrop master @return True if success/ | function pause() external onlyLinkdropMaster whenNotPaused returns (bool) {
_paused = true;
emit Paused(now);
return true;
}
| 14,052,050 | [
1,
2083,
358,
11722,
6835,
16,
848,
1338,
506,
2566,
635,
1692,
7285,
4171,
327,
1053,
309,
2216,
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,
11722,
1435,
3903,
1338,
2098,
7285,
7786,
1347,
1248,
28590,
1135,
261,
6430,
13,
288,
203,
3639,
389,
8774,
3668,
273,
638,
31,
203,
3639,
3626,
21800,
3668,
12,
3338,
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
] |
./partial_match/1/0xcDdc0F6053432dE3dd0F8dB3786D696fffC3A860/sources/OriginEthStrategy.sol | * @dev withdraw from strategy via curve swap @param baseAmount - base token amount/ | function _withdrawViaSwap(uint256 baseAmount) private returns(uint256, int256){
uint256 strategyTokenIn = _calcStrategyTokenWithdraw(baseAmount);
uint256 baseTrueOut = _swapToBase(strategyTokenIn, OETH);
int256 currentProfit = int256(baseTrueOut)- int256(baseAmount);
totalProfit += currentProfit;
depositedBase -= baseAmount;
return (baseTrueOut, currentProfit);
}
| 15,778,621 | [
1,
1918,
9446,
628,
6252,
3970,
8882,
7720,
225,
1026,
6275,
300,
1026,
1147,
3844,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1918,
9446,
21246,
12521,
12,
11890,
5034,
1026,
6275,
13,
3238,
1135,
12,
11890,
5034,
16,
509,
5034,
15329,
203,
3639,
2254,
5034,
6252,
1345,
382,
273,
389,
12448,
4525,
1345,
1190,
9446,
12,
1969,
6275,
1769,
203,
3639,
2254,
5034,
1026,
5510,
1182,
273,
389,
22270,
774,
2171,
12,
14914,
1345,
382,
16,
531,
1584,
44,
1769,
203,
3639,
509,
5034,
783,
626,
7216,
273,
509,
5034,
12,
1969,
5510,
1182,
24950,
509,
5034,
12,
1969,
6275,
1769,
203,
203,
3639,
2078,
626,
7216,
1011,
783,
626,
7216,
31,
203,
3639,
443,
1724,
329,
2171,
3947,
1026,
6275,
31,
203,
3639,
327,
261,
1969,
5510,
1182,
16,
783,
626,
7216,
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
] |
pragma solidity ^0.5.0;
interface JudgeInterface {
function judge(bytes32[13] calldata res, uint q,
bytes32[] calldata _proof, bytes32[] calldata _proof2,
bytes32 vm_, bytes32 op, uint[4] calldata regs,
bytes32[10] calldata roots, uint[4] calldata pointers) external returns (uint);
function judgeCustom(bytes32 state1, bytes32 state2, bytes32 ex_state, uint ex_reg, bytes32 op, uint[4] calldata regs,
bytes32[10] calldata roots, uint[4] calldata pointers, bytes32[] calldata proof) external;
function checkFileProof(bytes32 state, bytes32[10] calldata roots, uint[4] calldata pointers, bytes32[] calldata proof, uint loc) external returns (bool);
function checkProof(bytes32 hash, bytes32 root, bytes32[] calldata proof, uint loc) external returns (bool);
function calcStateHash(bytes32[10] calldata roots, uint[4] calldata pointers) external returns (bytes32);
function calcIOHash(bytes32[10] calldata roots) external returns (bytes32);
}
interface CustomJudge {
// Initializes a new custom verification game
function init(bytes32 state, uint state_size, uint r3, address solver, address verifier) external returns (bytes32);
// Last time the task was updated
function clock(bytes32 id) external returns (uint);
// Check if has resolved into correct state: merkle root of output data and output size
function resolved(bytes32 id, bytes32 state, uint size) external returns (bool);
}
// import "./../interface/IGameMaker.sol";
import "./../interface/IDisputeResolutionLayer.sol";
contract Interactive is IDispute {
constructor(address addr) public {
judge = JudgeInterface(addr);
}
JudgeInterface judge;
mapping (bytes32 => uint) blocked;
mapping (bytes32 => bool) rejected;
enum State {
Started,
Running, // First and last state have been set up ... but this will mean that the verification game is running now
Finished, // Winner has been chosen
NeedPhases,
PostedPhases,
SelectedPhase,
// Special states for custom judges
Custom
}
struct Game {
bytes32 task_id;
address prover;
address challenger;
bytes32 start_state; // actually initial code + input
bytes32 end_state; // actually output
// Maybe number of steps should be finished
uint256 steps;
address winner;
address next;
uint256 size;
uint256 timeout;
uint256 clock;
uint256 idx1;
uint256 idx2;
uint256 phase;
bytes32[] proof;
bytes32[13] result;
State state;
Status status;
// Needed for custom judges
CustomJudge judge;
bytes32 sub_task;
bytes32 ex_state; // result from the custom judge
uint ex_size;
}
mapping (bytes32 => Game) games;
mapping (uint64 => CustomJudge) judges;
uint counter;
// who should be able to register these
function registerJudge(uint64 id, address addr) public {
judges[id] = CustomJudge(addr);
}
event StartChallenge(address p, address c, bytes32 s, bytes32 e, uint256 par, uint to, bytes32 gameID);
event Reported(bytes32 gameID, uint idx1, uint idx2, bytes32[] arr);
event Queried(bytes32 gameID, uint idx1, uint idx2);
event PostedPhases(bytes32 gameID, uint idx1, bytes32[13] arr);
event SelectedPhase(bytes32 gameID, uint idx1, uint phase);
event WinnerSelected(bytes32 gameID);
event SubGoal(bytes32 gameID, uint64 judge, bytes32 init_data, uint init_size, bytes32 ret_data, uint ret_size);
function make(bytes32 taskID, address solver, address verifier, bytes32 startStateHash, bytes32 endStateHash, uint256 size, uint timeout) external returns (bytes32) {
bytes32 gameID = keccak256(abi.encodePacked(taskID, solver, verifier, startStateHash, endStateHash, size, timeout, counter));
counter++;
Game storage g = games[gameID];
g.task_id = taskID;
g.prover = solver;
g.challenger = verifier;
g.start_state = startStateHash;
g.end_state = endStateHash;
g.timeout = timeout;
g.next = g.prover;
g.idx1 = 0;
g.phase = 16;
g.size = size;
g.state = State.Started;
g.status = Status.Challenged;
g.clock = block.number;
blocked[taskID] = g.clock + g.timeout;
emit StartChallenge(solver, verifier, startStateHash, endStateHash, size, timeout, gameID);
return gameID;
}
function timeoutBlock(bytes32 gameID) external view returns (uint) {
Game storage g = games[gameID];
return g.clock + g.timeout;
}
function status(bytes32 gameID) external view returns(Status) {
return games[gameID].status;
}
uint constant FINAL_STATE = 0xffffffffff;
struct Roots {
bytes32 code;
bytes32 stack;
bytes32 mem;
bytes32 globals;
bytes32 calltable;
bytes32 calltypes;
bytes32 call_stack;
bytes32 input_size;
bytes32 input_name;
bytes32 input_data;
}
struct VM {
uint pc;
uint stack_ptr;
uint call_ptr;
uint memsize;
}
VM vm;
Roots vm_r;
function ccStateHash(bytes32[10] memory roots, uint[4] memory pointers) public returns (bytes32) {
vm_r.code = roots[0];
vm_r.stack = roots[1];
vm_r.mem = roots[2];
vm_r.call_stack = roots[3];
vm_r.globals = roots[4];
vm_r.calltable = roots[5];
vm_r.calltypes = roots[6];
vm_r.input_size = roots[7];
vm_r.input_name = roots[8];
vm_r.input_data = roots[9];
vm.pc = pointers[0];
vm.stack_ptr = pointers[1];
vm.call_ptr = pointers[2];
vm.memsize = pointers[3];
bytes32[] memory arr = new bytes32[](14);
arr[0] = vm_r.code;
arr[1] = vm_r.mem;
arr[2] = vm_r.stack;
arr[3] = vm_r.globals;
arr[4] = vm_r.call_stack;
arr[5] = vm_r.calltable;
arr[6] = vm_r.calltypes;
arr[7] = vm_r.input_size;
arr[8] = vm_r.input_name;
arr[9] = vm_r.input_data;
arr[0] = roots[0];
arr[1] = roots[2];
arr[2] = roots[1];
arr[3] = roots[4];
arr[4] = roots[3];
arr[5] = roots[5];
arr[6] = roots[6];
arr[7] = roots[7];
arr[8] = roots[8];
arr[9] = roots[9];
arr[10] = bytes32(vm.pc);
arr[11] = bytes32(vm.stack_ptr);
arr[12] = bytes32(vm.call_ptr);
arr[13] = bytes32(vm.memsize);
return keccak256(abi.encodePacked(arr));
}
function initialize(bytes32 gameID, bytes32[10] memory s_roots, uint[4] memory s_pointers, uint _steps, bytes32[10] memory e_roots, uint[4] memory e_pointers) public returns (bytes32[10] memory, uint[4] memory, bytes32, bytes32) {
Game storage g = games[gameID];
require(msg.sender == g.next && g.state == State.Started);
// check first state here
require (g.start_state == judge.calcIOHash(s_roots));
// then last one
require (g.end_state == judge.calcIOHash(e_roots));
// need to check that the start state is empty
// stack
require(s_roots[1] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
// memory
require(s_roots[2] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
// call stack
require(s_roots[3] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
// globals
require(s_roots[4] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
// call table (check if resizing works)
require(s_roots[5] == 0x7bf9aa8e0ce11d87877e8b7a304e8e7105531771dbff77d1b00366ecb1549624);
//require(s_roots[5] == 0xc024f071f70ef04cc1aaa7cb371bd1c4f7df06b0edb57b81adbcc9cdb1dfc910);
// call types
require(s_roots[6] == 0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30);
// pointers
require(s_pointers[0] == 0 && s_pointers[1] == 0 && s_pointers[2] == 0 && s_pointers[3] == 0);
// check final state
require(e_pointers[0] == FINAL_STATE);
// require(_steps < 2**34);
// Now we can initialize
g.steps = _steps;
if (g.size > g.steps - 2) g.size = g.steps-2;
g.idx2 = g.steps-1;
g.proof.length = g.steps;
g.proof[g.steps-1] = judge.calcStateHash(e_roots, e_pointers);
g.proof[0] = judge.calcStateHash(s_roots, s_pointers);
g.state = State.Running;
g.status = Status.Unresolved;
// return true;
return (e_roots, e_pointers, keccak256(abi.encodePacked(e_roots, e_pointers)), ccStateHash(e_roots, e_pointers));
}
function getDescription(bytes32 gameID) public view returns (bytes32 init, uint steps, bytes32 last) {
Game storage g = games[gameID];
return (g.proof[0], g.steps, g.proof[g.steps-1]);
}
function getChallenger(bytes32 gameID) public view returns (address) {
return games[gameID].challenger;
}
function getProver(bytes32 gameID) public view returns (address) {
return games[gameID].prover;
}
function getIndices(bytes32 gameID) public view returns (uint idx1, uint idx2) {
Game storage g = games[gameID];
return (g.idx1, g.idx2);
}
function getTask(bytes32 gameID) public view returns (bytes32) {
Game storage g = games[gameID];
return g.task_id;
}
function deleteChallenge(bytes32 gameID) public {
delete games[gameID];
}
function checkTimeout(bytes32 gameID) internal returns (bool) {
Game storage g = games[gameID];
if (g.state == State.Custom) return block.number >= g.judge.clock(g.sub_task) + g.timeout;
return block.number >= g.clock + g.timeout && g.state != State.Finished;
}
function gameOver(bytes32 gameID) public returns (bool) {
Game storage g = games[gameID];
if (!checkTimeout(gameID)) return false;
require(checkTimeout(gameID));
if (g.next == g.prover) {
g.winner = g.challenger;
g.status = Status.ChallengerWon;
rejected[g.task_id] = true;
}
else {
g.winner = g.prover;
g.status = Status.SolverWon;
blocked[g.task_id] = 0;
}
emit WinnerSelected(gameID);
g.state = State.Finished;
return true;
}
function clock(bytes32 gameID) public returns (uint) {
Game storage g = games[gameID];
if (g.sub_task != 0) return g.judge.clock(g.sub_task);
else return g.clock;
}
function isRejected(bytes32 gameID) public view returns (bool) {
return rejected[gameID];
}
function blockedTime(bytes32 gameID) public view returns (uint) {
return blocked[gameID];
}
function getIter(bytes32 gameID) internal view returns (uint it, uint i1, uint i2) {
Game storage g = games[gameID];
it = (g.idx2-g.idx1)/(g.size+1);
i1 = g.idx1;
i2 = g.idx2;
}
function report(bytes32 gameID, uint i1, uint i2, bytes32[] memory arr) public returns (bool) {
Game storage g = games[gameID];
require(g.state == State.Running && arr.length == g.size && i1 == g.idx1 && i2 == g.idx2 && msg.sender == g.prover && g.prover == g.next);
g.clock = block.number;
blocked[g.task_id] = g.clock + g.timeout;
uint iter = (g.idx2-g.idx1)/(g.size+1);
for (uint i = 0; i < arr.length; i++) {
g.proof[g.idx1+iter*(i+1)] = arr[i];
}
g.next = g.challenger;
emit Reported(gameID, i1, i2, arr);
return true;
}
function getStateAt(bytes32 gameID, uint loc) public view returns (bytes32) {
return games[gameID].proof[loc];
}
// TODO: check the array here, too
function query(bytes32 gameID, uint i1, uint i2, uint num) public {
Game storage g = games[gameID];
require(g.state == State.Running && num <= g.size && i1 == g.idx1 && i2 == g.idx2 && msg.sender == g.challenger && g.challenger == g.next);
g.clock = block.number;
blocked[g.task_id] = g.clock + g.timeout;
uint iter = (g.idx2-g.idx1)/(g.size+1);
g.idx1 = g.idx1+iter*num;
// If last segment was selected, do not change last index
if (num != g.size) g.idx2 = g.idx1+iter;
if (g.size > g.idx2-g.idx1-1) g.size = g.idx2-g.idx1-1;
// size eventually becomes zero here
g.next = g.prover;
emit Queried(gameID, g.idx1, g.idx2);
if (g.size == 0) g.state = State.NeedPhases;
}
function getStep(bytes32 gameID, uint idx) public view returns (bytes32) {
Game storage g = games[gameID];
return g.proof[idx];
}
function postPhases(bytes32 gameID, uint i1, bytes32[13] memory arr) public {
Game storage g = games[gameID];
require(g.state == State.NeedPhases && msg.sender == g.prover && g.next == g.prover && g.idx1 == i1);
require(g.proof[g.idx1] == arr[0] && g.proof[g.idx1+1] == arr[12] && arr[12] != bytes32(0));
g.clock = block.number;
g.state = State.PostedPhases;
blocked[g.task_id] = g.clock + g.timeout;
g.result = arr;
g.next = g.challenger;
emit PostedPhases(gameID, i1, arr);
}
function getResult(bytes32 gameID) public view returns (bytes32[13] memory) {
return games[gameID].result;
}
function selectPhase(bytes32 gameID, uint i1, bytes32 st, uint q) public {
Game storage g = games[gameID];
require(g.state == State.PostedPhases && msg.sender == g.challenger && g.idx1 == i1 && g.result[q] == st && g.next == g.challenger && q < 13);
g.clock = block.number;
blocked[g.task_id] = g.clock + g.timeout;
g.phase = q;
emit SelectedPhase(gameID, i1, q);
g.next = g.prover;
g.state = State.SelectedPhase;
}
function getState(bytes32 gameID) public view returns (State) {
return games[gameID].state;
}
function getPhase(bytes32 gameID) public view returns (uint) {
return games[gameID].phase;
}
function getWinner(bytes32 gameID) public view returns (address) {
return games[gameID].winner;
}
function callJudge(bytes32 gameID, uint i1, uint q, bytes32[] memory proof, bytes32[] memory proof2, bytes32 vmHash, bytes32 op, uint[4] memory regs, bytes32[10] memory roots, uint[4] memory pointers) public {
Game storage g = games[gameID];
require(g.state == State.SelectedPhase && g.phase == q && msg.sender == g.prover && g.idx1 == i1 && g.next == g.prover);
// for custom judge, use another method
// uint alu_hint = (uint(op)/2**(8*3))&0xff; require (q != 5 || alu_hint != 0xff);
judge.judge(g.result, g.phase, proof, proof2, vmHash, op, regs, roots, pointers);
emit WinnerSelected(gameID);
g.winner = g.prover;
g.status = Status.SolverWon;
blocked[g.task_id] = block.number + g.timeout;
g.state = State.Finished;
}
function resolveCustom(bytes32 gameID) public returns (bool) {
Game storage g = games[gameID];
if (g.sub_task == 0 || !g.judge.resolved(g.sub_task, g.ex_state, g.ex_size)) return false;
emit WinnerSelected(gameID);
g.winner = g.prover;
blocked[g.task_id] = block.number + g.timeout;
g.state = State.Finished;
g.status = Status.SolverWon;
return true;
}
// some register should have the input size?
function callCustomJudge(bytes32 gameID, uint i1, bytes32 op, uint[4] memory regs, bytes32 custom_result, uint custom_size, bytes32[] memory custom_proof, bytes32[10] memory roots, uint[4] memory pointers) public {
Game storage g = games[gameID];
require(g.state == State.SelectedPhase && g.phase == 6 && msg.sender == g.prover && g.idx1 == i1 && g.next == g.prover);
uint hint = (uint(op)/2**(8*5))&0xff;
require (hint == 0x16);
g.judge = judges[uint64(regs[3])];
// uint256 init_size = regs[0] % 2 == 0 ? uint(custom_size_proof[0]) : uint(custom_size_proof[1]);
bytes32 init_data = regs[0] % 2 == 0 ? custom_proof[0] : custom_proof[1];
g.sub_task = g.judge.init(init_data, regs[1], regs[2], g.prover, g.challenger);
g.ex_state = custom_result;
g.ex_size = custom_size;
judge.judgeCustom(g.result[5], g.result[6], custom_result, custom_size, op, regs, roots, pointers, custom_proof);
g.state = State.Custom;
emit SubGoal(gameID, uint64(regs[3]), init_data, regs[1], custom_result, custom_size);
}
function checkFileProof(bytes32 state, bytes32[10] memory roots, uint[4] memory pointers, bytes32[] memory proof, uint loc) public returns (bool) {
return judge.checkFileProof(state, roots, pointers, proof, loc);
}
function checkProof(bytes32 hash, bytes32 root, bytes32[] memory proof, uint loc) public returns (bool) {
return judge.checkProof(hash, root, proof, loc);
}
function calcStateHash(bytes32[10] memory roots, uint[4] memory pointers) public returns (bytes32) {
return judge.calcStateHash(roots, pointers);
}
}
| TODO: check the array here, too If last segment was selected, do not change last index size eventually becomes zero here | function query(bytes32 gameID, uint i1, uint i2, uint num) public {
Game storage g = games[gameID];
require(g.state == State.Running && num <= g.size && i1 == g.idx1 && i2 == g.idx2 && msg.sender == g.challenger && g.challenger == g.next);
g.clock = block.number;
blocked[g.task_id] = g.clock + g.timeout;
uint iter = (g.idx2-g.idx1)/(g.size+1);
g.idx1 = g.idx1+iter*num;
if (num != g.size) g.idx2 = g.idx1+iter;
if (g.size > g.idx2-g.idx1-1) g.size = g.idx2-g.idx1-1;
g.next = g.prover;
emit Queried(gameID, g.idx1, g.idx2);
if (g.size == 0) g.state = State.NeedPhases;
}
| 12,884,920 | [
1,
6241,
30,
866,
326,
526,
2674,
16,
4885,
971,
1142,
3267,
1703,
3170,
16,
741,
486,
2549,
1142,
770,
963,
18011,
12724,
3634,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
843,
12,
3890,
1578,
7920,
734,
16,
2254,
277,
21,
16,
2254,
277,
22,
16,
2254,
818,
13,
1071,
288,
203,
3639,
14121,
2502,
314,
273,
28422,
63,
13957,
734,
15533,
203,
3639,
2583,
12,
75,
18,
2019,
422,
3287,
18,
7051,
597,
818,
1648,
314,
18,
1467,
597,
277,
21,
422,
314,
18,
3465,
21,
597,
277,
22,
422,
314,
18,
3465,
22,
597,
1234,
18,
15330,
422,
314,
18,
343,
7862,
693,
597,
314,
18,
343,
7862,
693,
422,
314,
18,
4285,
1769,
203,
3639,
314,
18,
18517,
273,
1203,
18,
2696,
31,
203,
3639,
14547,
63,
75,
18,
4146,
67,
350,
65,
273,
314,
18,
18517,
397,
314,
18,
4538,
31,
203,
3639,
2254,
1400,
273,
261,
75,
18,
3465,
22,
17,
75,
18,
3465,
21,
13176,
12,
75,
18,
1467,
15,
21,
1769,
203,
3639,
314,
18,
3465,
21,
273,
314,
18,
3465,
21,
15,
2165,
14,
2107,
31,
203,
3639,
309,
261,
2107,
480,
314,
18,
1467,
13,
314,
18,
3465,
22,
273,
314,
18,
3465,
21,
15,
2165,
31,
203,
3639,
309,
261,
75,
18,
1467,
405,
314,
18,
3465,
22,
17,
75,
18,
3465,
21,
17,
21,
13,
314,
18,
1467,
273,
314,
18,
3465,
22,
17,
75,
18,
3465,
21,
17,
21,
31,
203,
3639,
314,
18,
4285,
273,
314,
18,
685,
502,
31,
203,
3639,
3626,
4783,
264,
2092,
12,
13957,
734,
16,
314,
18,
3465,
21,
16,
314,
18,
3465,
22,
1769,
203,
3639,
309,
261,
75,
18,
1467,
422,
374,
13,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/ICoverFeeReceiver.sol";
import "./interfaces/IRouter.sol";
import "./utils/Ownable.sol";
import "./ERC20/IERC20.sol";
import "./ERC20/SafeERC20.sol";
contract CoverFeeReceiver is Ownable, ICoverFeeReceiver {
using SafeERC20 for IERC20;
address public immutable override cover;
address public override forge;
address public override treasury;
uint256 public override feeNumToTreasury;
constructor(address _cover, address _forge, address _treasury, uint256 _feeNumToTreasury) {
require(_cover != address(0), "address cannot be 0");
require(_forge != address(0), "address cannot be 0");
require(_treasury != address(0), "address cannot be 0");
require(_feeNumToTreasury <= 10000, "_feeNumToTreasury must be <= 10000");
cover = _cover;
forge = _forge;
treasury = _treasury;
feeNumToTreasury = _feeNumToTreasury;
}
function buyBack(IERC20 _token, IRouter _router, address[] calldata _path, uint256 _maxSwapAmt, uint256 _amountOutMin) external override onlyOwner {
require(_path[0] == address(_token), "input token != _token");
require(_path[0] != cover, "input token cannot be COVER");
require(_path[_path.length - 1] == cover, "output token != COVER");
require(_maxSwapAmt > 0, "_maxSwapAmt <= 0");
uint256 balance = _token.balanceOf(address(this));
require(balance > 0, "_token balance is 0");
uint256 swapAmt = balance < _maxSwapAmt ? balance : _maxSwapAmt;
if (feeNumToTreasury > 0) {
uint256 amtToTreasury = swapAmt * feeNumToTreasury / 10000;
_token.safeTransfer(treasury, amtToTreasury);
swapAmt = swapAmt - amtToTreasury;
}
uint256 allowance = _token.allowance(address(this), address(_router));
if (allowance < swapAmt) {
if (allowance != 0) {
_token.safeApprove(address(_router), 0);
}
_token.safeApprove(address(_router), type(uint256).max);
}
_router.swapExactTokensForTokens(swapAmt, _amountOutMin, _path, forge, block.timestamp + 1 hours);
emit BuyBack(_token, swapAmt);
}
/// @notice For tokens that don't have enough liquidity to swap into COVER
function collect(IERC20 _token, uint256 _amount) external override onlyOwner {
uint256 balance = _token.balanceOf(address(this));
uint256 amount = _amount == 0 ? balance : _amount;
require(balance >= amount, "amount exceed balance");
_token.safeTransfer(treasury, amount);
emit Collected(_token, amount);
}
function setForge(address _forge) external override onlyOwner {
require(_forge != address(0), "address cannot be 0");
forge = _forge;
}
function setTreasury(address _treasury) external override onlyOwner {
require(_treasury != address(0), "address cannot be 0");
treasury = _treasury;
}
function setFeeNumToTreasury(uint256 _feeNumToTreasury) external override onlyOwner {
require(_feeNumToTreasury <= 10000, "_feeNumToTreasury must be <= 10000");
feeNumToTreasury = _feeNumToTreasury;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20/IERC20.sol";
import "./IRouter.sol";
interface ICoverFeeReceiver {
event BuyBack(IERC20 _token, uint256 _amount);
event Collected(IERC20 _token, uint256 _amount);
// state vars
function cover() external returns (address);
function forge() external returns (address);
function treasury() external returns (address);
function feeNumToTreasury() external returns (uint256);
// owner actions
function buyBack(IERC20 _token, IRouter _router, address[] calldata _path, uint256 _maxSwapAmt, uint256 _amountOutMin) external;
function collect(IERC20 _token, uint256 _amount) external;
function setForge(address _forge) external;
function setTreasury(address _treasury) external;
function setFeeNumToTreasury(uint256 _feeNumToTreasury) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRouter {
function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev 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) {
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.8.0;
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);
}
}
}
} | state vars owner actions | interface ICoverFeeReceiver {
event BuyBack(IERC20 _token, uint256 _amount);
event Collected(IERC20 _token, uint256 _amount);
function cover() external returns (address);
function forge() external returns (address);
function treasury() external returns (address);
function feeNumToTreasury() external returns (uint256);
function buyBack(IERC20 _token, IRouter _router, address[] calldata _path, uint256 _maxSwapAmt, uint256 _amountOutMin) external;
function collect(IERC20 _token, uint256 _amount) external;
function setForge(address _forge) external;
function setTreasury(address _treasury) external;
function setFeeNumToTreasury(uint256 _feeNumToTreasury) external;
}
| 9,952,673 | [
1,
2019,
4153,
3410,
4209,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
8084,
14667,
12952,
288,
203,
565,
871,
605,
9835,
2711,
12,
45,
654,
39,
3462,
389,
2316,
16,
2254,
5034,
389,
8949,
1769,
203,
565,
871,
9302,
329,
12,
45,
654,
39,
3462,
389,
2316,
16,
2254,
5034,
389,
8949,
1769,
203,
203,
565,
445,
5590,
1435,
3903,
1135,
261,
2867,
1769,
203,
565,
445,
21388,
1435,
3903,
1135,
261,
2867,
1769,
203,
565,
445,
9787,
345,
22498,
1435,
3903,
1135,
261,
2867,
1769,
203,
565,
445,
14036,
2578,
774,
56,
266,
345,
22498,
1435,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
30143,
2711,
12,
45,
654,
39,
3462,
389,
2316,
16,
467,
8259,
389,
10717,
16,
1758,
8526,
745,
892,
389,
803,
16,
2254,
5034,
389,
1896,
12521,
31787,
16,
2254,
5034,
389,
8949,
1182,
2930,
13,
3903,
31,
203,
565,
445,
3274,
12,
45,
654,
39,
3462,
389,
2316,
16,
2254,
5034,
389,
8949,
13,
3903,
31,
203,
565,
445,
444,
1290,
908,
12,
2867,
389,
1884,
908,
13,
3903,
31,
203,
565,
445,
444,
56,
266,
345,
22498,
12,
2867,
389,
27427,
345,
22498,
13,
3903,
31,
203,
565,
445,
444,
14667,
2578,
774,
56,
266,
345,
22498,
12,
11890,
5034,
389,
21386,
2578,
774,
56,
266,
345,
22498,
13,
3903,
31,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
/*
▄████████ ▄▄▄▄███▄▄▄▄ ▄██████▄ ▄█
███ ███ ▄██▀▀▀███▀▀▀██▄ ███ ███ ███
███ █▀ ███ ███ ███ ███ ███ ███
███ ███ ███ ███ ███ ███ ███
▀███████████ ███ ███ ███ ███ ███ ███
███ ███ ███ ███ ███ ███ ███
▄█ ███ ███ ███ ███ ███ ███ ███▌ ▄
▄████████▀ ▀█ ███ █▀ ▀██████▀ █████▄▄██
▀
▄█ █▄ ▄█ ███▄▄▄▄ ▄██████▄ ▄████████ ████████▄
███ ███ ███ ███▀▀▀██▄ ███ ███ ███ ███ ███ ▀███
███ ███ ███▌ ███ ███ ███ █▀ ███ █▀ ███ ███
███ ███ ███▌ ███ ███ ▄███ ▄███▄▄▄ ███ ███
███ ███ ███▌ ███ ███ ▀▀███ ████▄ ▀▀███▀▀▀ ███ ███
███ ███ ███ ███ ███ ███ ███ ███ █▄ ███ ███
███ ▄█▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▄███
▀███▀███▀ █▀ ▀█ █▀ ████████▀ ██████████ ████████▀
███ ███ █▄ ▄████████ ███ ▄█ ▄████████ ▄███████▄
▀█████████▄ ███ ███ ███ ███ ▀█████████▄ ███ ███ ███ ██▀ ▄██
▀███▀▀██ ███ ███ ███ ███ ▀███▀▀██ ███ ███ █▀ ▄███▀
███ ▀ ███ ███ ▄███▄▄▄▄██▀ ███ ▀ ███ ▄███▄▄▄ ▀█▀▄███▀▄▄
███ ███ ███ ▀▀███▀▀▀▀▀ ███ ███ ▀▀███▀▀▀ ▄███▀ ▀
███ ███ ███ ▀███████████ ███ ███ ███ █▄ ▄███▀
███ ███ ███ ███ ███ ███ ███▌ ▄ ███ ███ ███▄ ▄█
▄████▀ ████████▀ ███ ███ ▄████▀ █████▄▄██ ██████████ ▀████████▀
*/
// @title Smol Winged Turtlez
// @author @tom_hirst
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
import './SmolWingedTurtlezLibrary.sol';
import './Base64.sol';
contract SmolWingedTurtlez is ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _nextTokenId;
uint256 public maxSupply = 6969;
uint256 public constant TOKEN_PRICE = 0.02 ether;
struct Hash {
uint16 backgroundColor;
uint16 wingColor;
uint16 wingType;
bool bandana;
uint16 bandanaColor;
bool boots;
uint16 bootsColor;
uint16 pupil;
bool tongue;
bool tail;
}
struct Coordinates {
string x;
string y;
}
struct Color {
string hexCode;
string name;
}
Hash[] private tokenIdHash;
mapping(uint256 => Coordinates) private pupils;
mapping(uint256 => Coordinates[]) private wingTypes;
mapping(uint256 => Color[]) private colorPalettes;
string[] private wingTypeValues = [
'Regular',
'Long',
'Tall',
'Spiky',
'Ruffled',
'Loose Feathers',
'Sparkly',
'Claw'
];
string[] private pupilValues = ['Mindful', 'Positive', 'Reserved', 'Focused'];
uint16[][5] traitWeights;
function setPupil(
uint48 pupilIndex,
string memory x,
string memory y
) private {
pupils[pupilIndex] = Coordinates(x, y);
}
function setWingType(uint48 wingTypeIndex, Coordinates[3] memory coordinates) private {
for (uint8 i = 0; i < coordinates.length; i++) {
wingTypes[wingTypeIndex].push(coordinates[i]);
}
}
function setColorPalette(uint48 colorPaletteIndex, Color[8] memory colors) private {
for (uint8 i = 0; i < colors.length; i++) {
colorPalettes[colorPaletteIndex].push(colors[i]);
}
}
constructor() ERC721('Smol Winged Turtlez', 'SWT') {
// Start at token 1
_nextTokenId.increment();
// Dummy value to prevent need for offset
tokenIdHash.push(
Hash({
backgroundColor: 0,
wingType: 0,
wingColor: 0,
bandana: false,
bandanaColor: 0,
boots: false,
bootsColor: 0,
pupil: 0,
tongue: false,
tail: false
})
);
// Wing type rarity
traitWeights[0] = [1600, 1350, 1200, 1050, 850, 550, 369];
// Wing color rarity
traitWeights[1] = [3400, 2250, 1250, 69];
// Boots rarity
traitWeights[2] = [1500, 5469];
// Bandana rarity
traitWeights[3] = [2069, 4900];
// Tongue rarity
traitWeights[4] = [5000, 1969];
// Background colors
setColorPalette(
0,
[
Color({ hexCode: '#bcdfb9', name: 'Green' }),
Color({ hexCode: '#d5bada', name: 'Purple' }),
Color({ hexCode: '#ecc1db', name: 'Pink' }),
Color({ hexCode: '#e3c29e', name: 'Orange' }),
Color({ hexCode: '#84cfc6', name: 'Turquoise' }),
Color({ hexCode: '#faf185', name: 'Yellow' }),
Color({ hexCode: '#b0d9f4', name: 'Blue' }),
Color({ hexCode: '#444444', name: 'Black' })
]
);
// Accessory colors
setColorPalette(
1,
[
Color({ hexCode: '#567e39', name: 'Green' }),
Color({ hexCode: '#8c3895', name: 'Purple' }),
Color({ hexCode: '#ab62a8', name: 'Pink' }),
Color({ hexCode: '#da7327', name: 'Orange' }),
Color({ hexCode: '#00a794', name: 'Turquoise' }),
Color({ hexCode: '#decf22', name: 'Yellow' }),
Color({ hexCode: '#1b80c4', name: 'Blue' }),
Color({ hexCode: '#222222', name: 'Black' })
]
);
// Wing colors
setColorPalette(
2,
[
Color({ hexCode: '#ffffff', name: 'White' }),
Color({ hexCode: '#af8d56', name: 'Bronze' }),
Color({ hexCode: '#a7a5a5', name: 'Silver' }),
Color({ hexCode: '#d4af34', name: 'Gold' }),
Color({ hexCode: '#ffffff', name: 'White' }),
Color({ hexCode: '#af8d56', name: 'Bronze' }),
Color({ hexCode: '#a7a5a5', name: 'Silver' }),
Color({ hexCode: '#d4af34', name: 'Gold' })
]
);
// Mindful
setPupil(0, '16', '10');
// Positive
setPupil(1, '17', '10');
// Reserved
setPupil(2, '16', '11');
// Focused
setPupil(3, '17', '11');
// Regular
setWingType(
0,
[Coordinates({ x: '0', y: '0' }), Coordinates({ x: '0', y: '0' }), Coordinates({ x: '0', y: '0' })]
);
// Long
setWingType(
1,
[Coordinates({ x: '3', y: '8' }), Coordinates({ x: '4', y: '8' }), Coordinates({ x: '5', y: '8' })]
);
// Tall
setWingType(
2,
[Coordinates({ x: '5', y: '8' }), Coordinates({ x: '5', y: '7' }), Coordinates({ x: '5', y: '6' })]
);
// Spiky
setWingType(
3,
[Coordinates({ x: '4', y: '7' }), Coordinates({ x: '6', y: '7' }), Coordinates({ x: '8', y: '7' })]
);
// Ruffled
setWingType(
4,
[Coordinates({ x: '6', y: '7' }), Coordinates({ x: '9', y: '7' }), Coordinates({ x: '10', y: '6' })]
);
// Loose
setWingType(
5,
[Coordinates({ x: '8', y: '12' }), Coordinates({ x: '10', y: '12' }), Coordinates({ x: '12', y: '12' })]
);
// Sparkly
setWingType(
6,
[Coordinates({ x: '4', y: '6' }), Coordinates({ x: '2', y: '7' }), Coordinates({ x: '3', y: '8' })]
);
// Claw
setWingType(
7,
[Coordinates({ x: '4', y: '9' }), Coordinates({ x: '3', y: '10' }), Coordinates({ x: '5', y: '10' })]
);
}
function totalSupply() public view returns (uint256) {
return _nextTokenId.current() - 1;
}
function weightedRarityGenerator(uint16 pseudoRandomNumber, uint8 trait) internal view returns (uint16) {
uint16 lowerBound = 0;
for (uint8 i = 0; i < traitWeights[trait].length; i++) {
uint16 weight = traitWeights[trait][i];
if (pseudoRandomNumber >= lowerBound && pseudoRandomNumber < lowerBound + weight) {
return i;
}
lowerBound = lowerBound + weight;
}
revert();
}
function createTokenIdHash(uint256 tokenId) public view returns (Hash memory) {
uint256 pseudoRandomBase = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), tokenId)));
return
Hash({
backgroundColor: uint16(uint16(pseudoRandomBase) % 8),
wingType: weightedRarityGenerator(uint16(uint16(pseudoRandomBase) % 6969), 0),
wingColor: weightedRarityGenerator(uint16(uint16(pseudoRandomBase >> 48) % 6969), 1),
bandana: weightedRarityGenerator(uint16(uint16(pseudoRandomBase >> 96) % 6969), 2) == 1,
bandanaColor: uint16(uint16(pseudoRandomBase >> 144) % 8),
boots: weightedRarityGenerator(uint16(uint16(pseudoRandomBase >> 192) % 6969), 3) == 1,
bootsColor: uint16(uint16(pseudoRandomBase >> 240) % 8),
pupil: uint16(uint16(pseudoRandomBase) % 4),
tongue: weightedRarityGenerator(uint16(uint16(pseudoRandomBase) % 6969), 4) == 1,
tail: uint16(uint16(pseudoRandomBase) % 2) == 1
});
}
function getTokenIdHashSvg(Hash memory hash) public view returns (string memory svg) {
svg = string(
abi.encodePacked(
svg,
"<rect fill='",
colorPalettes[0][hash.backgroundColor].hexCode,
"' height='24' width='24' />",
"<rect fill='#567e39' height='1' width='4' x='9' y='9' />",
"<rect fill='#567e39' height='1' width='6' x='8' y='10' />",
"<rect fill='#567e39' height='3' width='8' x='7' y='11' />",
"<rect fill='#65bc48' height='1' width='3' x='15' y='9' />",
"<rect fill='#65bc48' height='3' width='4' x='15' y='10' />",
"<rect fill='#65bc48' height='1' width='3' x='15' y='13' />",
"<rect fill='#65bc48' height='1' width='8' x='7' y='14' />",
"<rect fill='#65bc48' height='1' width='2' x='7' y='15' />",
"<rect fill='#65bc48' height='1' width='2' x='13' y='15' />"
"<rect fill='#ffffff' height='2' width='2' x='16' y='10' />",
"<rect fill='",
colorPalettes[2][hash.wingColor].hexCode,
"' height='1' width='6' x='5' y='8' />",
"<rect fill='",
colorPalettes[2][hash.wingColor].hexCode,
"' height='1' width='4' x='7' y='9' />",
"<rect fill='",
colorPalettes[2][hash.wingColor].hexCode,
"' height='1' width='2' x='9' y='10' />",
"<rect fill='#65bc48' height='1' width='1' x='6' y='13' />",
"<rect fill='#000000' height='1' width='1' x='",
pupils[hash.pupil].x,
"' y='",
pupils[hash.pupil].y,
"' />"
)
);
if (hash.wingType != 0) {
for (uint8 i = 0; i < wingTypes[hash.wingType].length; i++) {
svg = string(
abi.encodePacked(
svg,
"<rect fill='",
colorPalettes[2][hash.wingColor].hexCode,
"' height='1' width='1' x='",
wingTypes[hash.wingType][i].x,
"' y='",
wingTypes[hash.wingType][i].y,
"' />"
)
);
}
}
if (hash.boots) {
svg = string(
abi.encodePacked(
svg,
"<rect fill='",
colorPalettes[1][hash.bootsColor].hexCode,
"' height='1' width='2' x='7' y='15' /><rect fill='",
colorPalettes[1][hash.bootsColor].hexCode,
"' height='1' width='2' x='13' y='15' />"
)
);
}
if (hash.bandana) {
svg = string(
abi.encodePacked(
svg,
"<rect fill='",
colorPalettes[1][hash.bandanaColor].hexCode,
"' height='1' width='1' x='14' y='8' /><rect fill='",
colorPalettes[1][hash.bandanaColor].hexCode,
"' height='1' width='3' x='15' y='9' />"
)
);
}
if (hash.tongue) {
svg = string(abi.encodePacked(svg, "<rect fill='#ed2024' height='1' width='1' x='18' y='13' />"));
}
if (hash.tail) {
svg = string(abi.encodePacked(svg, "<rect fill='#65bc48' height='1' width='1' x='5' y='12' />"));
} else {
svg = string(abi.encodePacked(svg, "<rect fill='#65bc48' height='1' width='1' x='5' y='14' />"));
}
return
string(
abi.encodePacked(
"<svg id='smol-winged-turtle' xmlns='http://www.w3.org/2000/svg' preserveAspectRatio='xMinYMin meet' viewBox='0 0 24 24'>",
svg,
'<style>#smol-winged-turtle{shape-rendering:crispedges;}</style></svg>'
)
);
}
function getTokenIdHashMetadata(Hash memory hash) public view returns (string memory metadata) {
metadata = string(
abi.encodePacked(
metadata,
'{"trait_type":"Background", "value":"',
colorPalettes[0][hash.backgroundColor].name,
'"},',
'{"trait_type":"Wing Type", "value":"',
wingTypeValues[hash.wingType],
'"},',
'{"trait_type":"Wing Color", "value":"',
colorPalettes[2][hash.wingColor].name,
'"},',
'{"trait_type":"Eyes", "value":"',
pupilValues[hash.pupil],
'"}'
)
);
if (hash.boots) {
metadata = string(
abi.encodePacked(
metadata,
',{"trait_type":"Boots", "value":"',
colorPalettes[1][hash.bootsColor].name,
'"}'
)
);
}
if (hash.bandana) {
metadata = string(
abi.encodePacked(
metadata,
',{"trait_type":"Bandana", "value":"',
colorPalettes[1][hash.bandanaColor].name,
'"}'
)
);
}
if (hash.tongue) {
metadata = string(abi.encodePacked(metadata, ',{"trait_type":"Tongue", "value":"True"}'));
}
if (hash.tail) {
metadata = string(abi.encodePacked(metadata, ',{"trait_type":"Tail", "value":"Up"}'));
} else {
metadata = string(abi.encodePacked(metadata, ',{"trait_type":"Tail", "value":"Down"}'));
}
return string(abi.encodePacked('[', metadata, ']'));
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId));
Hash memory hash = tokenIdHash[tokenId];
return
string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Smol Winged Turtle #',
SmolWingedTurtlezLibrary.toString(tokenId),
'", "description": "Smol Winged Turtlez is a collection of up to 6,969 fully on-chain characters that might be a great investment opportunity. Mint your turtlez before they fly away!", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(getTokenIdHashSvg(hash))),
'","attributes":',
getTokenIdHashMetadata(hash),
'}'
)
)
)
)
)
);
}
function mint(uint256 numberOfTokens) public payable {
require(numberOfTokens > 0, 'Quantity must be greater than 0.');
require(numberOfTokens < 6, 'Exceeds max per mint.');
require(totalSupply() + numberOfTokens <= maxSupply, 'Exceeds max supply.');
require(msg.value >= numberOfTokens * TOKEN_PRICE, 'Wrong ETH value sent.');
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 tokenId = _nextTokenId.current();
tokenIdHash.push(createTokenIdHash(tokenId));
_safeMint(msg.sender, tokenId);
_nextTokenId.increment();
}
}
function reduceSupply() external onlyOwner {
require(totalSupply() < maxSupply, 'All minted.');
maxSupply = totalSupply();
}
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
▄████████ ▄▄▄▄███▄▄▄▄ ▄██████▄ ▄█
███ ███ ▄██▀▀▀███▀▀▀██▄ ███ ███ ███
███ █▀ ███ ███ ███ ███ ███ ███
███ ███ ███ ███ ███ ███ ███
▀███████████ ███ ███ ███ ███ ███ ███
███ ███ ███ ███ ███ ███ ███
▄█ ███ ███ ███ ███ ███ ███ ███▌ ▄
▄████████▀ ▀█ ███ █▀ ▀██████▀ █████▄▄██
▀
▄█ █▄ ▄█ ███▄▄▄▄ ▄██████▄ ▄████████ ████████▄
███ ███ ███ ███▀▀▀██▄ ███ ███ ███ ███ ███ ▀███
███ ███ ███▌ ███ ███ ███ █▀ ███ █▀ ███ ███
███ ███ ███▌ ███ ███ ▄███ ▄███▄▄▄ ███ ███
███ ███ ███▌ ███ ███ ▀▀███ ████▄ ▀▀███▀▀▀ ███ ███
███ ███ ███ ███ ███ ███ ███ ███ █▄ ███ ███
███ ▄█▄ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▄███
▀███▀███▀ █▀ ▀█ █▀ ████████▀ ██████████ ████████▀
███ ███ █▄ ▄████████ ███ ▄█ ▄████████ ▄███████▄
▀█████████▄ ███ ███ ███ ███ ▀█████████▄ ███ ███ ███ ██▀ ▄██
▀███▀▀██ ███ ███ ███ ███ ▀███▀▀██ ███ ███ █▀ ▄███▀
███ ▀ ███ ███ ▄███▄▄▄▄██▀ ███ ▀ ███ ▄███▄▄▄ ▀█▀▄███▀▄▄
███ ███ ███ ▀▀███▀▀▀▀▀ ███ ███ ▀▀███▀▀▀ ▄███▀ ▀
███ ███ ███ ▀███████████ ███ ███ ███ █▄ ▄███▀
███ ███ ███ ███ ███ ███ ███▌ ▄ ███ ███ ███▄ ▄█
▄████▀ ████████▀ ███ ███ ▄████▀ █████▄▄██ ██████████ ▀████████▀
*/
// @title Smol Winged Turtlez Library
// @author @tom_hirst
pragma solidity ^0.8.9;
library SmolWingedTurtlezLibrary {
/**
* @dev Inspired by OraclizeAPI's implementation - MIT license
* @dev https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
*/
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);
}
}
// SPDX-License-Identifier: MIT
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
pragma solidity ^0.8.9;
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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | @notice Encodes some bytes to the base64 representation multiply by 4/3 rounded up Add some extra buffer at the end | 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);
}
| 1,174,732 | [
1,
19771,
2690,
1731,
358,
326,
1026,
1105,
4335,
10194,
635,
1059,
19,
23,
16729,
731,
1436,
2690,
2870,
1613,
622,
326,
679,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
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,
26028,
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,
527,
12,
659,
16,
471,
12,
81,
945,
12,
1289,
12,
2121,
5263,
16,
471,
12,
674,
86,
12,
2138,
16,
810,
3631,
374,
92,
23,
42,
3719,
3631,
374,
6356,
3719,
203,
7734,
596,
519,
699,
80,
12,
28,
16,
596,
13,
203,
7734,
596,
519,
527,
12,
659,
16,
471,
12,
81,
945,
12,
1289,
12,
2121,
5263,
16,
2
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol';
import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {LibUintToString} from './LibUintToString.sol';
import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
import {ArtistCreator} from './ArtistCreator.sol';
import {ECDSA} from '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
/// @title Artist
/// @author SoundXYZ - @gigamesh & @vigneshka
/// @notice This contract is used to create & sell song NFTs for the artist who owns the contract.
/// @dev Started as a fork of Mirror's Editions.sol https://github.com/mirror-xyz/editions-v1/blob/main/contracts/Editions.sol
contract ArtistV3 is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
// ================================
// TYPES
// ================================
using LibUintToString for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
using ECDSA for bytes32;
enum TimeType {
START,
END
}
// ============ Structs ============
struct Edition {
// The account that will receive sales revenue.
address payable fundingRecipient;
// The price at which each token will be sold, in ETH.
uint256 price;
// The number of tokens sold so far.
uint32 numSold;
// The maximum number of tokens that can be sold.
uint32 quantity;
// Royalty amount in bps
uint32 royaltyBPS;
// start timestamp of auction (in seconds since unix epoch)
uint32 startTime;
// end timestamp of auction (in seconds since unix epoch)
uint32 endTime;
// quantity of permissioned tokens
uint32 permissionedQuantity;
// whitelist signer address
address signerAddress;
}
// ================================
// STORAGE
// ================================
string internal baseURI;
CountersUpgradeable.Counter private atTokenId; // DEPRECATED IN V3
CountersUpgradeable.Counter private atEditionId;
// Mapping of edition id to descriptive data.
mapping(uint256 => Edition) public editions;
// <DEPRECATED IN V3> Mapping of token id to edition id.
mapping(uint256 => uint256) private _tokenToEdition;
// The amount of funds that have been deposited for a given edition.
mapping(uint256 => uint256) public depositedForEdition;
// The amount of funds that have already been withdrawn for a given edition.
mapping(uint256 => uint256) public withdrawnForEdition;
// The permissioned typehash (used for checking signature validity)
bytes32 private constant PERMISSIONED_SALE_TYPEHASH =
keccak256('EditionInfo(address contractAddress,address buyerAddress,uint256 editionId)');
bytes32 private immutable DOMAIN_SEPARATOR;
// ================================
// EVENTS
// ================================
event EditionCreated(
uint256 indexed editionId,
address fundingRecipient,
uint256 price,
uint32 quantity,
uint32 royaltyBPS,
uint32 startTime,
uint32 endTime,
uint32 permissionedQuantity,
address signerAddress
);
event EditionPurchased(
uint256 indexed editionId,
uint256 indexed tokenId,
// `numSold` at time of purchase represents the "serial number" of the NFT.
uint32 numSold,
// The account that paid for and received the NFT.
address indexed buyer
);
event AuctionTimeSet(TimeType timeType, uint256 editionId, uint32 indexed newTime);
event SignerAddressSet(uint256 editionId, address indexed signerAddress);
event PermissionedQuantitySet(uint256 editionId, uint32 permissionedQuantity);
// ================================
// PUBLIC & EXTERNAL WRITABLE FUNCTIONS
// ================================
/// @notice Contract constructor
constructor() {
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid));
}
/// @notice Initializes the contract
/// @param _owner Owner of edition
/// @param _name Name of artist
function initialize(
address _owner,
uint256 _artistId,
string memory _name,
string memory _symbol,
string memory _baseURI
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
// Set ownership to original sender of contract call
transferOwnership(_owner);
// E.g. https://sound.xyz/api/metadata/[artistId]/
baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/'));
// Set edition id start to be 1 not 0
atEditionId.increment();
}
/// @notice Creates a new edition.
/// @param _fundingRecipient The account that will receive sales revenue.
/// @param _price The price at which each token will be sold, in ETH.
/// @param _quantity The maximum number of tokens that can be sold.
/// @param _royaltyBPS The royalty amount in bps.
/// @param _startTime The start time of the auction, in seconds since unix epoch.
/// @param _endTime The end time of the auction, in seconds since unix epoch.
/// @param _permissionedQuantity The quantity of tokens that require a signature to buy.
/// @param _signerAddress signer address.
function createEdition(
address payable _fundingRecipient,
uint256 _price,
uint32 _quantity,
uint32 _royaltyBPS,
uint32 _startTime,
uint32 _endTime,
uint32 _permissionedQuantity,
address _signerAddress
) external onlyOwner {
require(_permissionedQuantity < _quantity + 1, 'Permissioned quantity too big');
require(_quantity > 0, 'Must set quantity');
require(_fundingRecipient != address(0), 'Must set fundingRecipient');
require(_endTime > _startTime, 'End time must be greater than start time');
if (_permissionedQuantity > 0) {
require(_signerAddress != address(0), 'Signer address cannot be 0');
}
editions[atEditionId.current()] = Edition({
fundingRecipient: _fundingRecipient,
price: _price,
numSold: 0,
quantity: _quantity,
royaltyBPS: _royaltyBPS,
startTime: _startTime,
endTime: _endTime,
permissionedQuantity: _permissionedQuantity,
signerAddress: _signerAddress
});
emit EditionCreated(
atEditionId.current(),
_fundingRecipient,
_price,
_quantity,
_royaltyBPS,
_startTime,
_endTime,
_permissionedQuantity,
_signerAddress
);
atEditionId.increment();
}
/// @notice Creates a new token for the given edition, and assigns it to the buyer
/// @param _editionId The id of the edition to purchase
/// @param _signature A signed message for authorizing permissioned purchases
function buyEdition(uint256 _editionId, bytes calldata _signature) external payable {
// Caching variables locally to reduce reads
uint256 price = editions[_editionId].price;
uint32 quantity = editions[_editionId].quantity;
uint32 numSold = editions[_editionId].numSold;
uint32 startTime = editions[_editionId].startTime;
uint32 endTime = editions[_editionId].endTime;
uint32 permissionedQuantity = editions[_editionId].permissionedQuantity;
// Check that the edition exists. Note: this is redundant
// with the next check, but it is useful for clearer error messaging.
require(quantity > 0, 'Edition does not exist');
// Check that there are still tokens available to purchase.
require(numSold < quantity, 'This edition is already sold out.');
// Check that the sender is paying the correct amount.
require(msg.value >= price, 'Must send enough to purchase the edition.');
// If the open auction hasn't started...
if (startTime > block.timestamp) {
// Check that permissioned tokens are still available
require(
permissionedQuantity > 0 && numSold < permissionedQuantity,
'No permissioned tokens available & open auction not started'
);
// Check that the signature is valid.
require(getSigner(_signature, _editionId) == editions[_editionId].signerAddress, 'Invalid signer');
}
// Don't allow purchases after the end time
require(endTime > block.timestamp, 'Auction has ended');
// Create the token id by packing editionId in the top bits
uint256 tokenId;
unchecked {
tokenId = (_editionId << 128) | (numSold + 1);
// Increment the number of tokens sold for this edition.
editions[_editionId].numSold = numSold + 1;
}
// If fundingRecipient is the owner (artist's wallet), update the edition's balance & don't send the funds
if (editions[_editionId].fundingRecipient == owner()) {
// Update the deposited total for the edition
depositedForEdition[_editionId] += msg.value;
} else {
// Send funds to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, msg.value);
}
// Mint a new token for the sender, using the `tokenId`.
_mint(msg.sender, tokenId);
emit EditionPurchased(_editionId, tokenId, editions[_editionId].numSold, msg.sender);
}
function withdrawFunds(uint256 _editionId) external {
// Compute the amount available for withdrawing from this edition.
uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId];
// Set the amount withdrawn to the amount deposited.
withdrawnForEdition[_editionId] = depositedForEdition[_editionId];
// Send the amount that was remaining for the edition, to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, remainingForEdition);
}
/// @notice Sets the start time for an edition
function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner {
editions[_editionId].startTime = _startTime;
emit AuctionTimeSet(TimeType.START, _editionId, _startTime);
}
/// @notice Sets the end time for an edition
function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner {
editions[_editionId].endTime = _endTime;
emit AuctionTimeSet(TimeType.END, _editionId, _endTime);
}
/// @notice Sets the signature address of an edition
function setSignerAddress(uint256 _editionId, address _newSignerAddress) external onlyOwner {
require(_newSignerAddress != address(0), 'Signer address cannot be 0');
editions[_editionId].signerAddress = _newSignerAddress;
emit SignerAddressSet(_editionId, _newSignerAddress);
}
/// @notice Sets the permissioned quantity for an edition
function setPermissionedQuantity(uint256 _editionId, uint32 _permissionedQuantity) external onlyOwner {
// Check that the permissioned quantity is less than the total quantity
require(_permissionedQuantity < editions[_editionId].quantity + 1, 'Must not exceed quantity');
// Prevent setting to permissioned quantity when there is no signer address
require(editions[_editionId].signerAddress != address(0), 'Edition must have a signer');
editions[_editionId].permissionedQuantity = _permissionedQuantity;
emit PermissionedQuantitySet(_editionId, _permissionedQuantity);
}
// ================================
// VIEW FUNCTIONS
// ================================
/// @notice Returns token URI (metadata URL). e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId]
/// @dev Concatenate the baseURI, editionId and tokenId, to create URI.
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
uint256 editionId = tokenToEdition(_tokenId);
return string(abi.encodePacked(baseURI, editionId.toString(), '/', _tokenId.toString()));
}
/// @notice Returns contract URI used by Opensea. e.g. https://sound.xyz/api/metadata/[artistId]/storefront
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseURI, 'storefront'));
}
/// @notice Get royalty information for token
/// @param _tokenId token id
/// @param _salePrice Sale price for the token
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address fundingRecipient, uint256 royaltyAmount)
{
uint256 editionId = tokenToEdition(_tokenId);
Edition memory edition = editions[editionId];
if (edition.fundingRecipient == address(0x0)) {
return (edition.fundingRecipient, 0);
}
uint256 royaltyBPS = uint256(edition.royaltyBPS);
return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000);
}
/// @notice The total number of tokens created by this contract
function totalSupply() external view returns (uint256) {
uint256 total = 0;
for (uint256 id = 1; id < atEditionId.current(); id++) {
total += editions[id].numSold;
}
return total;
}
/// @notice Informs other contracts which interfaces this contract supports
/// @dev https://eips.ethereum.org/EIPS/eip-165
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId);
}
/// @notice returns the number of editions for this artist
function editionCount() external view returns (uint256) {
return atEditionId.current() - 1; // because atEditionId is incremented after each edition is created
}
function tokenToEdition(uint256 _tokenId) public view returns (uint256) {
// Check the top bits to see if the edition id is there
uint256 editionId = _tokenId >> 128;
// If edition ID is 0, then this edition was created before the V3 upgrade
if (editionId == 0) {
// get edition ID from storage
return _tokenToEdition[_tokenId];
}
return editionId;
}
function ownersOfTokenIds(uint256[] calldata _tokenIds) external view returns (address[] memory) {
address[] memory owners = new address[](_tokenIds.length);
for (uint256 i = 0; i < _tokenIds.length; i++) {
owners[i] = ownerOf(_tokenIds[i]);
}
return owners;
}
// ================================
// FUNCTIONS - PRIVATE
// ================================
/// @notice Sends funds to an address
/// @param _recipient The address to send funds to
/// @param _amount The amount of funds to send
function _sendFunds(address payable _recipient, uint256 _amount) private {
require(address(this).balance >= _amount, 'Insufficient balance for send');
(bool success, ) = _recipient.call{value: _amount}('');
require(success, 'Unable to send value: recipient may have reverted');
}
/// @notice Gets signer address to validate permissioned purchase
/// @param _signature signed message
/// @param _editionId edition id
/// @return address of signer
/// @dev https://eips.ethereum.org/EIPS/eip-712
function getSigner(bytes calldata _signature, uint256 _editionId) private view returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMISSIONED_SALE_TYPEHASH, address(this), msg.sender, _editionId))
)
);
address recoveredAddress = digest.recover(_signature);
return recoveredAddress;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @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
// OpenZeppelin Contracts v4.4.1 (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 {
__Context_init_unchained();
__ERC165_init_unchained();
__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);
}
/**
* @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);
}
/**
* @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 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(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 {}
uint256[44] 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 {
__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;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
library LibUintToString {
uint256 private constant MAX_UINT256_STRING_LENGTH = 78;
uint8 private constant ASCII_DIGIT_OFFSET = 48;
/// @dev Converts a `uint256` value to a string.
/// @param n The integer to convert.
/// @return nstr `n` as a decimal string.
function toString(uint256 n) internal pure returns (string memory nstr) {
if (n == 0) {
return '0';
}
// Overallocate memory
nstr = new string(MAX_UINT256_STRING_LENGTH);
uint256 k = MAX_UINT256_STRING_LENGTH;
// Populate string from right to left (lsb to msb).
while (n != 0) {
assembly {
let char := add(ASCII_DIGIT_OFFSET, mod(n, 10))
mstore(add(nstr, k), char)
k := sub(k, 1)
n := div(n, 10)
}
}
assembly {
// Shift pointer over to actual start of string.
nstr := add(nstr, k)
// Store actual string length.
mstore(nstr, sub(MAX_UINT256_STRING_LENGTH, k))
}
return nstr;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';
import '@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol';
import '@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol';
import './Artist.sol';
contract ArtistCreator is Initializable, UUPSUpgradeable, OwnableUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
using ECDSAUpgradeable for bytes32;
// ============ Storage ============
bytes32 public constant MINTER_TYPEHASH = keccak256('Deployer(address artistWallet)');
CountersUpgradeable.Counter private atArtistId;
// address used for signature verification, changeable by owner
address public admin;
bytes32 public DOMAIN_SEPARATOR;
address public beaconAddress;
// registry of created contracts
address[] public artistContracts;
// ============ Events ============
/// Emitted when an Artist is created
event CreatedArtist(uint256 artistId, string name, string symbol, address indexed artistAddress);
// ============ Functions ============
/// Initializes factory
function initialize() public initializer {
__Ownable_init_unchained();
// set admin for artist deployment authorization
admin = msg.sender;
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid));
// set up beacon with msg.sender as the owner
UpgradeableBeacon _beacon = new UpgradeableBeacon(address(new Artist()));
_beacon.transferOwnership(msg.sender);
beaconAddress = address(_beacon);
// Set artist id start to be 1 not 0
atArtistId.increment();
}
/// Creates a new artist 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 artist
function createArtist(
bytes calldata signature,
string memory _name,
string memory _symbol,
string memory _baseURI
) public returns (address) {
require((getSigner(signature) == admin), 'invalid authorization signature');
BeaconProxy proxy = new BeaconProxy(
beaconAddress,
abi.encodeWithSelector(
Artist(address(0)).initialize.selector,
msg.sender,
atArtistId.current(),
_name,
_symbol,
_baseURI
)
);
// add to registry
artistContracts.push(address(proxy));
emit CreatedArtist(atArtistId.current(), _name, _symbol, address(proxy));
atArtistId.increment();
return address(proxy);
}
/// Get signer address of signature
function getSigner(bytes calldata signature) public view returns (address) {
require(admin != address(0), 'whitelist not enabled');
// Verify EIP-712 signature by recreating the data structure
// that we signed on the client side, and then using that to recover
// the address that signed the signature for this data.
bytes32 digest = keccak256(
abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender)))
);
// Use the recover method to see what address was used to create
// the signature on this data.
// Note that if the digest doesn't exactly match what was signed we'll
// get a random recovered address.
address recoveredAddress = digest.recover(signature);
return recoveredAddress;
}
/// Sets the admin for authorizing artist deployment
/// @param _newAdmin address of new admin
function setAdmin(address _newAdmin) external {
require(owner() == _msgSender() || admin == _msgSender(), 'invalid authorization');
admin = _newAdmin;
}
function _authorizeUpgrade(address) internal override onlyOwner {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
// 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 (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 v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) payable {
assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
_upgradeBeaconToAndCall(beacon, data, false);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address) {
return _getBeacon();
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
_upgradeBeaconToAndCall(beacon, data, false);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../../access/Ownable.sol";
import "../../utils/Address.sol";
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, Ownable {
address private _implementation;
/**
* @dev Emitted when the implementation returned by the beacon is changed.
*/
event Upgraded(address indexed implementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
constructor(address implementation_) {
_setImplementation(implementation_);
}
/**
* @dev Returns the current implementation address.
*/
function implementation() public view virtual override returns (address) {
return _implementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newImplementation` must be a contract.
*/
function upgradeTo(address newImplementation) public virtual onlyOwner {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newImplementation` must be a contract.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
_implementation = newImplementation;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol';
import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {Strings} from './Strings.sol';
import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
// This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol
/**
* @title Artist
* @author SoundXYZ
*/
contract Artist is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
// todo (optimization): link Strings as a deployed library
using Strings for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
// ============ Structs ============
struct Edition {
// The account that will receive sales revenue.
address payable fundingRecipient;
// The price at which each token will be sold, in ETH.
uint256 price;
// The number of tokens sold so far.
uint32 numSold;
// The maximum number of tokens that can be sold.
uint32 quantity;
// Royalty amount in bps
uint32 royaltyBPS;
// start timestamp of auction (in seconds since unix epoch)
uint32 startTime;
// end timestamp of auction (in seconds since unix epoch)
uint32 endTime;
}
// ============ Storage ============
string internal baseURI;
CountersUpgradeable.Counter private atTokenId;
CountersUpgradeable.Counter private atEditionId;
// Mapping of edition id to descriptive data.
mapping(uint256 => Edition) public editions;
// Mapping of token id to edition id.
mapping(uint256 => uint256) public tokenToEdition;
// The amount of funds that have been deposited for a given edition.
mapping(uint256 => uint256) public depositedForEdition;
// The amount of funds that have already been withdrawn for a given edition.
mapping(uint256 => uint256) public withdrawnForEdition;
// ============ Events ============
event EditionCreated(
uint256 indexed editionId,
address fundingRecipient,
uint256 price,
uint32 quantity,
uint32 royaltyBPS,
uint32 startTime,
uint32 endTime
);
event EditionPurchased(
uint256 indexed editionId,
uint256 indexed tokenId,
// `numSold` at time of purchase represents the "serial number" of the NFT.
uint32 numSold,
// The account that paid for and received the NFT.
address indexed buyer
);
// ============ Methods ============
/**
@param _owner Owner of edition
@param _name Name of artist
*/
function initialize(
address _owner,
uint256 _artistId,
string memory _name,
string memory _symbol,
string memory _baseURI
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
// Set ownership to original sender of contract call
transferOwnership(_owner);
// E.g. https://sound.xyz/api/metadata/[artistId]/
baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/'));
// Set token id start to be 1 not 0
atTokenId.increment();
// Set edition id start to be 1 not 0
atEditionId.increment();
}
function createEdition(
address payable _fundingRecipient,
uint256 _price,
uint32 _quantity,
uint32 _royaltyBPS,
uint32 _startTime,
uint32 _endTime
) external onlyOwner {
editions[atEditionId.current()] = Edition({
fundingRecipient: _fundingRecipient,
price: _price,
numSold: 0,
quantity: _quantity,
royaltyBPS: _royaltyBPS,
startTime: _startTime,
endTime: _endTime
});
emit EditionCreated(
atEditionId.current(),
_fundingRecipient,
_price,
_quantity,
_royaltyBPS,
_startTime,
_endTime
);
atEditionId.increment();
}
function buyEdition(uint256 _editionId) external payable {
// Check that the edition exists. Note: this is redundant
// with the next check, but it is useful for clearer error messaging.
require(editions[_editionId].quantity > 0, 'Edition does not exist');
// Check that there are still tokens available to purchase.
require(editions[_editionId].numSold < editions[_editionId].quantity, 'This edition is already sold out.');
// Check that the sender is paying the correct amount.
require(msg.value >= editions[_editionId].price, 'Must send enough to purchase the edition.');
// Don't allow purchases before the start time
require(editions[_editionId].startTime < block.timestamp, "Auction hasn't started");
// Don't allow purchases after the end time
require(editions[_editionId].endTime > block.timestamp, 'Auction has ended');
// Mint a new token for the sender, using the `tokenId`.
_mint(msg.sender, atTokenId.current());
// Update the deposited total for the edition
depositedForEdition[_editionId] += msg.value;
// Increment the number of tokens sold for this edition.
editions[_editionId].numSold++;
// Store the mapping of token id to the edition being purchased.
tokenToEdition[atTokenId.current()] = _editionId;
emit EditionPurchased(_editionId, atTokenId.current(), editions[_editionId].numSold, msg.sender);
atTokenId.increment();
}
// ============ Operational Methods ============
function withdrawFunds(uint256 _editionId) external {
// Compute the amount available for withdrawing from this edition.
uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId];
// Set the amount withdrawn to the amount deposited.
withdrawnForEdition[_editionId] = depositedForEdition[_editionId];
// Send the amount that was remaining for the edition, to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, remainingForEdition);
}
function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner {
editions[_editionId].startTime = _startTime;
}
function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner {
editions[_editionId].endTime = _endTime;
}
// ============ NFT Methods ============
// Returns e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId]
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
// Concatenate the components, baseURI, editionId and tokenId, to create URI.
return string(abi.encodePacked(baseURI, tokenToEdition[_tokenId].toString(), '/', _tokenId.toString()));
}
// Returns e.g. https://sound.xyz/api/metadata/[artistId]/storefront
function contractURI() public view returns (string memory) {
// Concatenate the components, baseURI, editionId and tokenId, to create URI.
return string(abi.encodePacked(baseURI, 'storefront'));
}
// ============ Extensions =================
/**
@dev Get token ids for a given edition id
@param _editionId edition id
*/
function getTokenIdsOfEdition(uint256 _editionId) public view returns (uint256[] memory) {
uint256[] memory tokenIdsOfEdition = new uint256[](editions[_editionId].numSold);
uint256 index = 0;
for (uint256 id = 1; id < atTokenId.current(); id++) {
if (tokenToEdition[id] == _editionId) {
tokenIdsOfEdition[index] = id;
index++;
}
}
return tokenIdsOfEdition;
}
/**
@dev Get owners of a given edition id
@param _editionId edition id
*/
function getOwnersOfEdition(uint256 _editionId) public view returns (address[] memory) {
address[] memory ownersOfEdition = new address[](editions[_editionId].numSold);
uint256 index = 0;
for (uint256 id = 1; id < atTokenId.current(); id++) {
if (tokenToEdition[id] == _editionId) {
ownersOfEdition[index] = ERC721Upgradeable.ownerOf(id);
index++;
}
}
return ownersOfEdition;
}
/**
@dev Get royalty information for token
@param _editionId edition id
@param _salePrice Sale price for the token
*/
function royaltyInfo(uint256 _editionId, uint256 _salePrice)
external
view
override
returns (address fundingRecipient, uint256 royaltyAmount)
{
Edition memory edition = editions[_editionId];
if (edition.fundingRecipient == address(0x0)) {
return (edition.fundingRecipient, 0);
}
uint256 royaltyBPS = uint256(edition.royaltyBPS);
return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000);
}
function totalSupply() external view returns (uint256) {
return atTokenId.current() - 1; // because atTokenId is 1-indexed
}
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId);
}
// ============ Private Methods ============
function _sendFunds(address payable _recipient, uint256 _amount) private {
require(address(this).balance >= _amount, 'Insufficient balance for send');
(bool success, ) = _recipient.call{value: _amount}('');
require(success, 'Unable to send value: recipient may have reverted');
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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: GPL-3.0-or-later
pragma solidity 0.8.7;
// This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol
/**
* @title Utils
* @author SoundXYZ
*/
library Strings {
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
} | * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by {upgradeTo} and {upgradeToAndCall}. Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. ```solidity function _authorizeUpgrade(address) internal override onlyOwner {} ```/ SPDX-License-Identifier: MIT OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. These functions can be used to verify that a message was signed by the holder of the private keys of a given address./ | library ECDSAUpgradeable {
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
revert("ECDSA: invalid signature");
revert("ECDSA: invalid signature length");
revert("ECDSA: invalid signature 's' value");
revert("ECDSA: invalid signature 'v' value");
}
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
revert("ECDSA: invalid signature");
revert("ECDSA: invalid signature length");
revert("ECDSA: invalid signature 's' value");
revert("ECDSA: invalid signature 'v' value");
}
}
} else if (error == RecoverError.InvalidSignature) {
} else if (error == RecoverError.InvalidSignatureLength) {
} else if (error == RecoverError.InvalidSignatureS) {
} else if (error == RecoverError.InvalidSignatureV) {
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
bytes32 r;
bytes32 vs;
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
return (address(0), RecoverError.InvalidSignatureLength);
}
}
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
bytes32 r;
bytes32 vs;
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
return (address(0), RecoverError.InvalidSignatureLength);
}
}
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
bytes32 r;
bytes32 vs;
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
return (address(0), RecoverError.InvalidSignatureLength);
}
}
} else if (signature.length == 64) {
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
bytes32 r;
bytes32 vs;
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
return (address(0), RecoverError.InvalidSignatureLength);
}
}
} else {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
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);
}
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);
}
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
address signer = ecrecover(hash, v, r, s);
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
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;
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
| 5,724,280 | [
1,
2083,
716,
1410,
15226,
1347,
1375,
3576,
18,
15330,
68,
353,
486,
10799,
358,
8400,
326,
6835,
18,
11782,
635,
288,
15097,
774,
97,
471,
288,
15097,
774,
1876,
1477,
5496,
24773,
1230,
16,
333,
445,
903,
999,
392,
15187,
30,
3860,
18,
4539,
63,
3860,
3325,
65,
9606,
4123,
487,
288,
5460,
429,
17,
3700,
5541,
5496,
31621,
30205,
560,
445,
389,
22488,
10784,
12,
2867,
13,
2713,
3849,
1338,
5541,
2618,
31621,
19,
11405,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
3502,
62,
881,
84,
292,
267,
30131,
331,
24,
18,
24,
18,
21,
261,
5471,
19,
22784,
15669,
19,
7228,
19748,
18,
18281,
13,
225,
10426,
549,
21507,
22901,
11678,
7053,
9249,
15067,
261,
7228,
19748,
13,
5295,
18,
8646,
4186,
848,
506,
1399,
358,
3929,
716,
279,
883,
1703,
6726,
635,
326,
10438,
434,
326,
3238,
1311,
434,
279,
864,
1758,
18,
19,
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,
12083,
7773,
19748,
10784,
429,
288,
203,
565,
445,
389,
22488,
10784,
12,
2867,
394,
13621,
13,
2713,
5024,
31,
203,
565,
2254,
5034,
63,
3361,
65,
3238,
1001,
14048,
31,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
315,
6216,
7957,
10784,
429,
18,
18281,
14432,
203,
203,
565,
2792,
868,
3165,
668,
288,
203,
3639,
2631,
668,
16,
203,
3639,
1962,
5374,
16,
203,
3639,
1962,
5374,
1782,
16,
203,
3639,
1962,
5374,
55,
16,
203,
3639,
1962,
5374,
58,
203,
565,
289,
203,
203,
565,
445,
389,
12849,
668,
12,
27622,
668,
555,
13,
3238,
16618,
288,
203,
3639,
309,
261,
1636,
422,
868,
3165,
668,
18,
2279,
668,
13,
288,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
8863,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
769,
8863,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
296,
87,
11,
460,
8863,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
296,
90,
11,
460,
8863,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
12849,
668,
12,
27622,
668,
555,
13,
3238,
16618,
288,
203,
3639,
309,
261,
1636,
422,
868,
3165,
668,
18,
2279,
668,
13,
288,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
8863,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
769,
8863,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
296,
87,
11,
460,
8863,
203,
5411,
15226,
2932,
7228,
19748,
30,
2057,
3372,
296,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
//
// This contract handles swapping to and from PlatinumNugget, LuckySwap's staking token.
contract AlchemyBench is ERC20("AlchemyBench", "PLAN"){
using SafeMath for uint256;
IERC20 public goldnugget;
// Define the GoldNugget token contract
constructor(IERC20 _goldnugget) public {
goldnugget = _goldnugget;
}
// Enter the alchemybench. Pay some GOLNs. Earn some shares.
// Locks GoldNugget and mints PlatinumNugget
function enter(uint256 _amount) public {
// Gets the amount of GoldNugget locked in the contract
uint256 totalGoldNugget = goldnugget.balanceOf(address(this));
// Gets the amount of PlatinumNugget in existence
uint256 totalShares = totalSupply();
// If no PlatinumNugget exists, mint it 1:1 to the amount put in
if (totalShares == 0 || totalGoldNugget == 0) {
_mint(msg.sender, _amount);
}
// Calculate and mint the amount of PlatinumNugget the GoldNugget is worth. The ratio will change overtime, as PlatinumNugget is burned/minted and GoldNugget deposited + gained from fees / withdrawn.
else {
uint256 what = _amount.mul(totalShares).div(totalGoldNugget);
_mint(msg.sender, what);
}
// Lock the GoldNugget in the contract
goldnugget.transferFrom(msg.sender, address(this), _amount);
}
// Leave the alchemybench. Claim back your GOLNs.
// Unlocks the staked + gained GoldNugget and burns PlatinumNugget
function leave(uint256 _share) public {
// Gets the amount of PlatinumNugget in existence
uint256 totalShares = totalSupply();
// Calculates the amount of GoldNugget the PlatinumNugget is worth
uint256 what = _share.mul(goldnugget.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
goldnugget.transfer(msg.sender, what);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol
// Copyright 2020 Compound Labs, Inc.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// XXX: pragma solidity ^0.5.16;
pragma solidity 0.6.12;
// XXX: import "./SafeMath.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 2 days;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
bool public admin_initialized;
mapping (bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
admin_initialized = false;
}
// XXX: function() external payable { }
receive() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
// allows one time setting of admin for deployment purposes
if (admin_initialized) {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
} else {
require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin.");
admin_initialized = true;
}
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// 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 (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Router01.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./uniswapv2/libraries/UniswapV2Library.sol";
// Ingot helps your migrate your existing Uniswap LP tokens to LuckySwap LP ones
contract Ingot {
using SafeERC20 for IERC20;
IUniswapV2Router01 public oldRouter;
IUniswapV2Router01 public router;
constructor(IUniswapV2Router01 _oldRouter, IUniswapV2Router01 _router) public {
oldRouter = _oldRouter;
router = _router;
}
function migrateWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));
pair.permit(msg.sender, address(this), liquidity, deadline, v, r, s);
migrate(tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline);
}
// msg.sender should have approved 'liquidity' amount of LP token of 'tokenA' and 'tokenB'
function migrate(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
) public {
require(deadline >= block.timestamp, 'LuckySwap: EXPIRED');
// Remove liquidity from the old router with permit
(uint256 amountA, uint256 amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
deadline
);
// Add liquidity to the new router
(uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB);
// Send remaining tokens to msg.sender
if (amountA > pooledAmountA) {
IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA);
}
if (amountB > pooledAmountB) {
IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB);
}
}
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
) internal returns (uint256 amountA, uint256 amountB) {
IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB));
pair.transferFrom(msg.sender, address(pair), liquidity);
(uint256 amount0, uint256 amount1) = pair.burn(address(this));
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'Ingot: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'Ingot: INSUFFICIENT_B_AMOUNT');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForOldRouter(address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
oldRouter.factory(),
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired
) internal returns (uint amountA, uint amountB) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired);
address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB);
IERC20(tokenA).safeTransfer(pair, amountA);
IERC20(tokenB).safeTransfer(pair, amountB);
IUniswapV2Pair(pair).mint(msg.sender);
}
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired
) internal returns (uint256 amountA, uint256 amountB) {
// create the pair if it doesn't exist yet
IUniswapV2Factory factory = IUniswapV2Factory(router.factory());
if (factory.getPair(tokenA, tokenB) == address(0)) {
factory.createPair(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
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
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);
}
// SPDX-License-Identifier: GPL-3.0
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 migrator() 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 setMigrator(address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
import '../interfaces/IUniswapV2Pair.sol';
import "./SafeMath.sol";
library UniswapV2Library {
using SafeMathUniswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathUniswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './libraries/UniswapV2Library.sol';
import './libraries/SafeMath.sol';
import './libraries/TransferHelper.sol';
import './interfaces/IUniswapV2Router02.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
contract UniswapV2Router02 is IUniswapV2Router02 {
using SafeMathUniswap for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IUniswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = UniswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IUniswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
(address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, 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 virtual override returns (uint amountA, uint amountB) {
address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = UniswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = UniswapV2Library.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return UniswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return UniswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
// SPDX-License-Identifier: GPL-3.0
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, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IERC20Uniswap {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
contract UniswapV2Pair is UniswapV2ERC20 {
using SafeMathUniswap for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
address migrator = IUniswapV2Factory(factory).migrator();
if (msg.sender == migrator) {
liquidity = IMigrator(migrator).desiredLiquidity();
require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity");
} else {
require(migrator == address(0), "Must not have migrator");
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
}
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './libraries/SafeMath.sol';
contract UniswapV2ERC20 {
using SafeMathUniswap for uint;
string public constant name = 'LuckySwap LP Token';
string public constant symbol = 'SLP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../uniswapv2/UniswapV2Pair.sol";
contract LuckySwapPairMock is UniswapV2Pair {
constructor() public UniswapV2Pair() {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./libraries/SafeMath.sol";
import "./libraries/SafeERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./Ownable.sol";
interface IAlpineWithdraw {
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
}
interface IGoldVeinWithdrawFee {
function asset() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function withdrawFees() external;
function removeAsset(address to, uint256 fraction) external returns (uint256 share);
}
// SmelterGoldVein is GoldMiner's left hand and kinda a wizard. He can cook up GoldNugget from pretty much anything!
// This contract handles "serving up" rewards for PlatinumNugget holders by trading tokens collected from Gold Vein fees for GoldNugget.
contract SmelterGoldVein is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IUniswapV2Factory private immutable factory;
//0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac
address private immutable alchemybench;
//0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272
IAlpineWithdraw private immutable alPine;
//0xF5BCE5077908a1b7370B9ae04AdC565EBd643966
address private immutable goldnugget;
//0xc6D69475f115F61B1e8C4e78c20C49201c869DB4
address private immutable weth;
//0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
bytes32 private immutable pairCodeHash;
//0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303
mapping(address => address) private _bridges;
event LogBridgeSet(address indexed token, address indexed bridge);
event LogConvert(
address indexed server,
address indexed token0,
uint256 amount0,
uint256 amountALP,
uint256 amountGOLN
);
constructor(
IUniswapV2Factory _factory,
address _alchemybench,
IAlpineWithdraw _alPine,
address _goldnugget,
address _weth,
bytes32 _pairCodeHash
) public {
factory = _factory;
alchemybench = _alchemybench;
alPine = _alPine;
goldnugget = _goldnugget;
weth = _weth;
pairCodeHash = _pairCodeHash;
}
function setBridge(address token, address bridge) external onlyOwner {
// Checks
require(
token != goldnugget && token != weth && token != bridge,
"Smelter: Invalid bridge"
);
// Effects
_bridges[token] = bridge;
emit LogBridgeSet(token, bridge);
}
modifier onlyEOA() {
// Try to make flash-loan exploit harder to do by only allowing externally-owned addresses.
require(msg.sender == tx.origin, "Smelter: Must use EOA");
_;
}
function convert(IGoldVeinWithdrawFee goldveinPair) external onlyEOA {
_convert(goldveinPair);
}
function convertMultiple(IGoldVeinWithdrawFee[] calldata goldveinPair) external onlyEOA {
for (uint256 i = 0; i < goldveinPair.length; i++) {
_convert(goldveinPair[i]);
}
}
function _convert(IGoldVeinWithdrawFee goldveinPair) private {
// update Gold Vein fees for this Smelter contract (`feeTo`)
goldveinPair.withdrawFees();
// convert updated Gold Vein balance to Alp shares
uint256 alpShares = goldveinPair.removeAsset(address(this), goldveinPair.balanceOf(address(this)));
// convert Alp shares to underlying Gold Vein asset (`token0`) balance (`amount0`) for Smelter
address token0 = goldveinPair.asset();
(uint256 amount0, ) = alPine.withdraw(IERC20(token0), address(this), address(this), 0, alpShares);
emit LogConvert(
msg.sender,
token0,
amount0,
alpShares,
_convertStep(token0, amount0)
);
}
function _convertStep(address token0, uint256 amount0) private returns (uint256 goldnuggetOut) {
if (token0 == goldnugget) {
IERC20(token0).safeTransfer(alchemybench, amount0);
goldnuggetOut = amount0;
} else if (token0 == weth) {
goldnuggetOut = _swap(token0, goldnugget, amount0, alchemybench);
} else {
address bridge = _bridges[token0];
if (bridge == address(0)) {
bridge = weth;
}
uint256 amountOut = _swap(token0, bridge, amount0, address(this));
goldnuggetOut = _convertStep(bridge, amountOut);
}
}
function _swap(
address fromToken,
address toToken,
uint256 amountIn,
address to
) private returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
IUniswapV2Pair pair =
IUniswapV2Pair(
uint256(
keccak256(abi.encodePacked(hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// 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");}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "SafeMath: uint128 Overflow");
c = uint128(a);
}
}
library SafeMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a + b) >= b, "SafeMath: Add Overflow");}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a - b) <= a, "SafeMath: Underflow");}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../interfaces/IERC20.sol";
library SafeERC20 {
function safeSymbol(IERC20 token) internal view returns(string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeName(IERC20 token) internal view returns(string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeDecimals(IERC20 token) public view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
function safeTransfer(IERC20 token, address to, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed");
}
function safeTransferFrom(IERC20 token, address from, uint256 amount) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed");
}
}
// SPDX-License-Identifier: MIT
// Audit on 5-Jan-2021 by Keno and BoringCrypto
// P1 - P3: OK
pragma solidity 0.6.12;
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol
// Edited by BoringCrypto
// T1 - T4: OK
contract OwnableData {
// V1 - V5: OK
address public owner;
// V1 - V5: OK
address public pendingOwner;
}
// T1 - T4: OK
contract Ownable is OwnableData {
// E1: OK
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
// F1 - F9: OK
// C1 - C21: OK
function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "Ownable: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
} else {
// Effects
pendingOwner = newOwner;
}
}
// F1 - F9: OK
// C1 - C21: OK
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
// M1 - M5: OK
// C1 - C21: OK
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
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;
}
// SPDX-License-Identifier: MIT
// P1 - P3: OK
pragma solidity 0.6.12;
import "./libraries/SafeMath.sol";
import "./libraries/SafeERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2ERC20.sol";
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
import "./Ownable.sol";
// Smelter is GoldMiner's left hand and kinda a wizard. He can cook up GoldNugget from pretty much anything!
// This contract handles "serving up" rewards for PlatinumNugget holders by trading tokens collected from fees for GoldNugget.
// T1 - T4: OK
contract Smelter is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// V1 - V5: OK
IUniswapV2Factory public immutable factory;
//0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac
// V1 - V5: OK
address public immutable alchemybench;
//0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272
// V1 - V5: OK
address private immutable goldnugget;
//0xc6D69475f115F61B1e8C4e78c20C49201c869DB4
// V1 - V5: OK
address private immutable weth;
//0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
// V1 - V5: OK
mapping(address => address) internal _bridges;
// E1: OK
event LogBridgeSet(address indexed token, address indexed bridge);
// E1: OK
event LogConvert(
address indexed server,
address indexed token0,
address indexed token1,
uint256 amount0,
uint256 amount1,
uint256 amountGOLN
);
constructor(
address _factory,
address _alchemybench,
address _goldnugget,
address _weth
) public {
factory = IUniswapV2Factory(_factory);
alchemybench = _alchemybench;
goldnugget = _goldnugget;
weth = _weth;
}
// F1 - F10: OK
// C1 - C24: OK
function bridgeFor(address token) public view returns (address bridge) {
bridge = _bridges[token];
if (bridge == address(0)) {
bridge = weth;
}
}
// F1 - F10: OK
// C1 - C24: OK
function setBridge(address token, address bridge) external onlyOwner {
// Checks
require(
token != goldnugget && token != weth && token != bridge,
"Smelter: Invalid bridge"
);
// Effects
_bridges[token] = bridge;
emit LogBridgeSet(token, bridge);
}
// M1 - M5: OK
// C1 - C24: OK
// C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin
modifier onlyEOA() {
// Try to make flash-loan exploit harder to do by only allowing externally owned addresses.
require(msg.sender == tx.origin, "Smelter: must use EOA");
_;
}
// F1 - F10: OK
// F3: _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple
// F6: There is an exploit to add lots of GOLN to the alchemybench, run convert, then remove the GOLN again.
// As the size of the AlchemyBench has grown, this requires large amounts of funds and isn't super profitable anymore
// The onlyEOA modifier prevents this being done with a flash loan.
// C1 - C24: OK
function convert(address token0, address token1) external onlyEOA() {
_convert(token0, token1);
}
// F1 - F10: OK, see convert
// C1 - C24: OK
// C3: Loop is under control of the caller
function convertMultiple(
address[] calldata token0,
address[] calldata token1
) external onlyEOA() {
// TODO: This can be optimized a fair bit, but this is safer and simpler for now
uint256 len = token0.length;
for (uint256 i = 0; i < len; i++) {
_convert(token0[i], token1[i]);
}
}
// F1 - F10: OK
// C1- C24: OK
function _convert(address token0, address token1) internal {
// Interactions
// S1 - S4: OK
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));
require(address(pair) != address(0), "Smelter: Invalid pair");
// balanceOf: S1 - S4: OK
// transfer: X1 - X5: OK
IERC20(address(pair)).safeTransfer(
address(pair),
pair.balanceOf(address(this))
);
// X1 - X5: OK
(uint256 amount0, uint256 amount1) = pair.burn(address(this));
if (token0 != pair.token0()) {
(amount0, amount1) = (amount1, amount0);
}
emit LogConvert(
msg.sender,
token0,
token1,
amount0,
amount1,
_convertStep(token0, token1, amount0, amount1)
);
}
// F1 - F10: OK
// C1 - C24: OK
// All safeTransfer, _swap, _toGOLN, _convertStep: X1 - X5: OK
function _convertStep(
address token0,
address token1,
uint256 amount0,
uint256 amount1
) internal returns (uint256 goldnuggetOut) {
// Interactions
if (token0 == token1) {
uint256 amount = amount0.add(amount1);
if (token0 == goldnugget) {
IERC20(goldnugget).safeTransfer(alchemybench, amount);
goldnuggetOut = amount;
} else if (token0 == weth) {
goldnuggetOut = _toGOLN(weth, amount);
} else {
address bridge = bridgeFor(token0);
amount = _swap(token0, bridge, amount, address(this));
goldnuggetOut = _convertStep(bridge, bridge, amount, 0);
}
} else if (token0 == goldnugget) {
// eg. GOLN - ETH
IERC20(goldnugget).safeTransfer(alchemybench, amount0);
goldnuggetOut = _toGOLN(token1, amount1).add(amount0);
} else if (token1 == goldnugget) {
// eg. USDT - GOLN
IERC20(goldnugget).safeTransfer(alchemybench, amount1);
goldnuggetOut = _toGOLN(token0, amount0).add(amount1);
} else if (token0 == weth) {
// eg. ETH - USDC
goldnuggetOut = _toGOLN(
weth,
_swap(token1, weth, amount1, address(this)).add(amount0)
);
} else if (token1 == weth) {
// eg. USDT - ETH
goldnuggetOut = _toGOLN(
weth,
_swap(token0, weth, amount0, address(this)).add(amount1)
);
} else {
// eg. MIC - USDT
address bridge0 = bridgeFor(token0);
address bridge1 = bridgeFor(token1);
if (bridge0 == token1) {
// eg. MIC - USDT - and bridgeFor(MIC) = USDT
goldnuggetOut = _convertStep(
bridge0,
token1,
_swap(token0, bridge0, amount0, address(this)),
amount1
);
} else if (bridge1 == token0) {
// eg. WBTC - DSD - and bridgeFor(DSD) = WBTC
goldnuggetOut = _convertStep(
token0,
bridge1,
amount0,
_swap(token1, bridge1, amount1, address(this))
);
} else {
goldnuggetOut = _convertStep(
bridge0,
bridge1, // eg. USDT - DSD - and bridgeFor(DSD) = WBTC
_swap(token0, bridge0, amount0, address(this)),
_swap(token1, bridge1, amount1, address(this))
);
}
}
}
// F1 - F10: OK
// C1 - C24: OK
// All safeTransfer, swap: X1 - X5: OK
function _swap(
address fromToken,
address toToken,
uint256 amountIn,
address to
) internal returns (uint256 amountOut) {
// Checks
// X1 - X5: OK
IUniswapV2Pair pair =
IUniswapV2Pair(factory.getPair(fromToken, toToken));
require(address(pair) != address(0), "Smelter: Cannot convert");
// Interactions
// X1 - X5: OK
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (fromToken == pair.token0()) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, new bytes(0));
// TODO: Add maximum slippage?
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, new bytes(0));
// TODO: Add maximum slippage?
}
}
// F1 - F10: OK
// C1 - C24: OK
function _toGOLN(address token, uint256 amountIn)
internal
returns (uint256 amountOut)
{
// X1 - X5: OK
amountOut = _swap(token, goldnugget, amountIn, alchemybench);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./uniswapv2/interfaces/IUniswapV2Pair.sol";
import "./uniswapv2/interfaces/IUniswapV2Factory.sol";
contract Migrator {
address public miner;
address public oldFactory;
IUniswapV2Factory public factory;
uint256 public notBeforeBlock;
uint256 public desiredLiquidity = uint256(-1);
constructor(
address _miner,
address _oldFactory,
IUniswapV2Factory _factory,
uint256 _notBeforeBlock
) public {
miner = _miner;
oldFactory = _oldFactory;
factory = _factory;
notBeforeBlock = _notBeforeBlock;
}
function migrate(IUniswapV2Pair orig) public returns (IUniswapV2Pair) {
require(msg.sender == miner, "not from gold miner");
require(block.number >= notBeforeBlock, "too early to migrate");
require(orig.factory() == oldFactory, "not from old factory");
address token0 = orig.token0();
address token1 = orig.token1();
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1));
if (pair == IUniswapV2Pair(address(0))) {
pair = IUniswapV2Pair(factory.createPair(token0, token1));
}
uint256 lp = orig.balanceOf(msg.sender);
if (lp == 0) return pair;
desiredLiquidity = lp;
orig.transferFrom(msg.sender, address(orig), lp);
orig.burn(address(pair));
pair.mint(msg.sender);
desiredLiquidity = uint256(-1);
return pair;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../Smelter.sol";
contract SmelterExploitMock {
Smelter public immutable smelTer;
constructor (address _smelTer) public{
smelTer = Smelter(_smelTer);
}
function convert(address token0, address token1) external {
smelTer.convert(token0, token1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../SmelterGoldVein.sol";
contract SmelterGoldVeinExploitMock {
SmelterGoldVein public immutable smelTer;
constructor(address _smelTer) public {
smelTer = SmelterGoldVein(_smelTer);
}
function convert(IGoldVeinWithdrawFee goldveinPair) external {
smelTer.convert(goldveinPair);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
address public override feeTo;
address public override feeToSetter;
address public override migrator;
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function pairCodeHash() external pure returns (bytes32) {
return keccak256(type(UniswapV2Pair).creationCode);
}
function createPair(address tokenA, address tokenB) external override returns (address pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
UniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setMigrator(address _migrator) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
migrator = _migrator;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../uniswapv2/UniswapV2Factory.sol";
contract LuckySwapFactoryMock is UniswapV2Factory {
constructor(address _feeToSetter) public UniswapV2Factory(_feeToSetter) {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./GoldNugget.sol";
interface IMigratorMiner {
// Perform LP token migration from legacy UniswapV2 to LuckySwap.
// 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 UniswapV2 LP tokens.
// LuckySwap must mint EXACTLY the same amount of LuckySwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
contract GoldMiner is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of GOLNs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accGoldNuggetPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accGoldNuggetPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. GOLNs to distribute per block.
uint256 lastRewardBlock; // Last block number that GOLNs distribution occurs.
uint256 accGoldNuggetPerShare; // Accumulated GOLNs per share, times 1e12. See below.
}
// The GOLN TOKEN!
GoldNugget public goldnugget;
// Dev address.
address public devaddr;
// Block number when bonus GOLN period ends.
uint256 public bonusEndBlock;
// GOLN tokens created per block.
uint256 public goldnuggetPerBlock;
// Bonus muliplier for early goldnugget smelter.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorMiner public migrator;
// 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 GOLN mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
GoldNugget _goldnugget,
address _devaddr,
uint256 _goldnuggetPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
goldnugget = _goldnugget;
devaddr = _devaddr;
goldnuggetPerBlock = _goldnuggetPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accGoldNuggetPerShare: 0
})
);
}
// Update the given pool's GOLN 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(IMigratorMiner _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];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return
bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending GOLNs on frontend.
function pendingGoldNugget(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accGoldNuggetPerShare = pool.accGoldNuggetPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier =
getMultiplier(pool.lastRewardBlock, block.number);
uint256 goldnuggetReward =
multiplier.mul(goldnuggetPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
accGoldNuggetPerShare = accGoldNuggetPerShare.add(
goldnuggetReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accGoldNuggetPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 goldnuggetReward =
multiplier.mul(goldnuggetPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
goldnugget.mint(devaddr, goldnuggetReward.div(10));
goldnugget.mint(address(this), goldnuggetReward);
pool.accGoldNuggetPerShare = pool.accGoldNuggetPerShare.add(
goldnuggetReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to GoldMiner for GOLN allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending =
user.amount.mul(pool.accGoldNuggetPerShare).div(1e12).sub(
user.rewardDebt
);
safeGoldNuggetTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accGoldNuggetPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from GoldMiner.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending =
user.amount.mul(pool.accGoldNuggetPerShare).div(1e12).sub(
user.rewardDebt
);
safeGoldNuggetTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGoldNuggetPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe goldnugget transfer function, just in case if rounding error causes pool to not have enough GOLNs.
function safeGoldNuggetTransfer(address _to, uint256 _amount) internal {
uint256 goldnuggetBal = goldnugget.balanceOf(address(this));
if (_amount > goldnuggetBal) {
goldnugget.transfer(_to, goldnuggetBal);
} else {
goldnugget.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
// 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 "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// GoldNugget with Governance.
contract GoldNugget is ERC20("GoldNugget", "GOLN"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (GoldMiner).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GOLN::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "GOLN::delegateBySig: invalid nonce");
require(now <= expiry, "GOLN::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "GOLN::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying GOLNs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "GOLN::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ERC20Mock is ERC20 {
constructor(
string memory name,
string memory symbol,
uint256 supply
) public ERC20(name, symbol) {
_mint(msg.sender, supply);
}
}
| * @notice Delegates votes from signatory to `delegatee` @param delegatee The address to delegate votes to @param nonce The contract state required to match the signature @param expiry The time at which to expire the signature @param v The recovery byte of the signature @param r Half of the ECDSA signature pair @param s Half of the ECDSA signature pair/ | function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GOLN::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "GOLN::delegateBySig: invalid nonce");
require(now <= expiry, "GOLN::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 176,024 | [
1,
15608,
815,
19588,
628,
1573,
8452,
358,
1375,
22216,
73,
68,
225,
7152,
73,
1021,
1758,
358,
7152,
19588,
358,
225,
7448,
1021,
6835,
919,
1931,
358,
845,
326,
3372,
225,
10839,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7152,
858,
8267,
12,
203,
3639,
1758,
7152,
73,
16,
203,
3639,
2254,
7448,
16,
203,
3639,
2254,
10839,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
203,
3639,
3903,
203,
565,
288,
203,
3639,
1731,
1578,
2461,
6581,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
27025,
67,
2399,
15920,
16,
203,
7734,
417,
24410,
581,
5034,
12,
3890,
12,
529,
10756,
3631,
203,
7734,
30170,
548,
9334,
203,
7734,
1758,
12,
2211,
13,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
1958,
2310,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
2030,
19384,
2689,
67,
2399,
15920,
16,
203,
7734,
7152,
73,
16,
203,
7734,
7448,
16,
203,
7734,
10839,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
1548,
92,
3657,
64,
92,
1611,
3113,
203,
7734,
2461,
6581,
16,
203,
7734,
1958,
2310,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1758,
1573,
8452,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
2977,
8452,
480,
1758,
12,
20,
3631,
315,
43,
1741,
50,
2866,
22216,
858,
8267,
30,
2057,
3372,
8863,
203,
3639,
2583,
12,
12824,
422,
1661,
764,
63,
2977,
8452,
3737,
15,
16,
315,
43,
1741,
50,
2866,
22216,
2
] |
pragma solidity >0.5.4;
import "@daostack/arc/contracts/controller/Avatar.sol";
import "@daostack/arc/contracts/controller/ControllerInterface.sol";
import "../../identity/Identity.sol";
import "../../identity/IdentityGuard.sol";
import "./SchemeGuard.sol";
/* @title Scheme contract responsible for adding address given
* in constructor to identity admins.
*/
contract AddAdmin is SchemeGuard, IdentityGuard {
Identity public identity;
address public admin;
/* @dev Constructor. Requires given address to be a valid address
* @param _avatar The avatar of the DAO
* @param _identity The identity contract
* @param _admin The address to add to admins
*/
constructor(
Avatar _avatar,
Identity _identity,
address _admin
) public SchemeGuard(_avatar) IdentityGuard(_identity) {
require(_admin != address(0), "admin cannot be null address");
identity = _identity;
admin = _admin;
}
/* @dev starts scheme if registered by DAO, gets avatar to add the
* address to list of identity admins and then self-destructs, sending
* all remaining eth to the address of the DAO avatar.
*/
function start() public onlyRegistered {
controller.genericCall(
address(identity),
abi.encodeWithSignature("addIdentityAdmin(address)", admin),
avatar,
0
);
selfdestruct(address(avatar));
}
}
| @title Scheme contract responsible for adding address given in constructor to identity admins./ | contract AddAdmin is SchemeGuard, IdentityGuard {
Identity public identity;
address public admin;
constructor(
Avatar _avatar,
Identity _identity,
address _admin
) public SchemeGuard(_avatar) IdentityGuard(_identity) {
require(_admin != address(0), "admin cannot be null address");
identity = _identity;
admin = _admin;
}
function start() public onlyRegistered {
controller.genericCall(
address(identity),
abi.encodeWithSignature("addIdentityAdmin(address)", admin),
avatar,
0
);
selfdestruct(address(avatar));
}
}
| 12,638,500 | [
1,
9321,
6835,
14549,
364,
6534,
1758,
864,
316,
3885,
358,
4215,
31116,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1436,
4446,
353,
10714,
16709,
16,
7808,
16709,
288,
203,
565,
7808,
1071,
4215,
31,
203,
565,
1758,
1071,
3981,
31,
203,
203,
565,
3885,
12,
203,
3639,
8789,
8761,
389,
19660,
16,
203,
3639,
7808,
389,
10781,
16,
203,
3639,
1758,
389,
3666,
203,
565,
262,
1071,
10714,
16709,
24899,
19660,
13,
7808,
16709,
24899,
10781,
13,
288,
203,
3639,
2583,
24899,
3666,
480,
1758,
12,
20,
3631,
315,
3666,
2780,
506,
446,
1758,
8863,
203,
3639,
4215,
273,
389,
10781,
31,
203,
3639,
3981,
273,
389,
3666,
31,
203,
565,
289,
203,
203,
565,
445,
787,
1435,
1071,
1338,
10868,
288,
203,
3639,
2596,
18,
13540,
1477,
12,
203,
5411,
1758,
12,
10781,
3631,
203,
5411,
24126,
18,
3015,
1190,
5374,
2932,
1289,
4334,
4446,
12,
2867,
2225,
16,
3981,
3631,
203,
5411,
16910,
16,
203,
5411,
374,
203,
3639,
11272,
203,
203,
3639,
365,
5489,
8813,
12,
2867,
12,
19660,
10019,
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
] |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IStakingContract.sol";
import "./IStakeChangeNotifier.sol";
contract StakingContract is IStakingContract, IMigratableStakingContract {
using SafeMath for uint256;
struct Stake {
uint256 amount;
uint256 cooldownAmount;
uint256 cooldownEndTime;
}
struct WithdrawResult {
uint256 withdrawnAmount;
uint256 stakedAmount;
uint256 stakedAmountDiff;
}
// The version of the smart contract.
uint256 public constant VERSION = 1;
// The maximum number of approved staking contracts as migration destinations.
uint256 public constant MAX_APPROVED_STAKING_CONTRACTS = 10;
// The mapping between stake owners and their data.
mapping(address => Stake) internal stakes;
// Total amount of staked tokens (not including unstaked tokes in cooldown or pending withdrawal).
uint256 internal totalStakedTokens;
// The period (in seconds) between a stake owner's request to stop staking and being able to withdraw them.
uint256 public cooldownPeriodInSec;
// The address responsible for managing migration to a new staking contract.
address public migrationManager;
// The address responsible for emergency operations and graceful return of staked tokens back to their owners.
address public emergencyManager;
// The list of staking contracts that are approved by this contract. It would be only allowed to migrate a stake to
// one of these contracts.
IMigratableStakingContract[] public approvedStakingContracts;
// The address of the contract responsible for publishing stake change notifications.
IStakeChangeNotifier public notifier;
// The address of the $EDI Token Contract
IERC20 internal token;
// Represents whether the contract accepts new staking requests. Please note, that even when it's turned off,
// it'd be still possible to unstake or withdraw tokens.
//
// Note: This can be turned off only once by the emergency manager of the contract.
bool public acceptingNewStakes = true;
// Represents whether this staking contract allows releasing all unstaked tokens unconditionally. When it's turned
// on, stake owners could release their staked tokens, without explicitly requesting to unstake them, and their
// previously unstaked tokens, regardless of the cooldown period. This also stops the contract from accepting new
// stakes.
//
// Note: This can be turned off only once by the emergency manager of the contract.
bool public releasingAllStakes = false;
event MigrationManagerUpdated(address indexed migrationManager);
event MigrationDestinationAdded(
IMigratableStakingContract indexed stakingContract
);
event MigrationDestinationRemoved(
IMigratableStakingContract indexed stakingContract
);
event EmergencyManagerUpdated(address indexed emergencyManager);
event StakeChangeNotifierUpdated(IStakeChangeNotifier indexed notifier);
event StoppedAcceptingNewStake();
event ReleasedAllStakes();
modifier onlyMigrationManager() {
require(
msg.sender == migrationManager,
"StakingContract: caller is not the migration manager"
);
_;
}
modifier onlyEmergencyManager() {
require(
msg.sender == emergencyManager,
"StakingContract: caller is not the emergency manager"
);
_;
}
modifier onlyWhenAcceptingNewStakes() {
require(
acceptingNewStakes && !releasingAllStakes,
"StakingContract: not accepting new stakes"
);
_;
}
modifier onlyWhenStakesReleased() {
require(
releasingAllStakes,
"StakingContract: not releasing all stakes"
);
_;
}
modifier onlyWhenStakesNotReleased() {
require(!releasingAllStakes, "StakingContract: releasing all stakes");
_;
}
/// @dev Initializes the staking contract.
/// @param _cooldownPeriodInSec uint256 The period (in seconds) between a stake owner's request to stop staking and being
/// able to withdraw them.
/// @param _migrationManager address The address responsible for managing migration to a new staking contract.
/// @param _emergencyManager address The address responsible for emergency operations and graceful return of staked
/// tokens back to their owners.
/// @param _token IERC20 The address of the $EDI Token
constructor(
uint256 _cooldownPeriodInSec,
address _migrationManager,
address _emergencyManager,
IERC20 _token
) public {
require(
_cooldownPeriodInSec > 0,
"StakingContract::ctor - cooldown period must be greater than 0"
);
require(
_migrationManager != address(0),
"StakingContract::ctor - migration manager must not be 0"
);
require(
_emergencyManager != address(0),
"StakingContract::ctor - emergency manager must not be 0"
);
require(
address(_token) != address(0),
"StakingContract::ctor - $EDI token must not be 0"
);
cooldownPeriodInSec = _cooldownPeriodInSec;
migrationManager = _migrationManager;
emergencyManager = _emergencyManager;
token = _token;
}
/// @dev Sets the address of the migration manager.
/// @param _newMigrationManager address The address of the new migration manager.
function setMigrationManager(address _newMigrationManager)
external
onlyMigrationManager
{
require(
_newMigrationManager != address(0),
"StakingContract::setMigrationManager - address must not be 0"
);
require(
migrationManager != _newMigrationManager,
"StakingContract::setMigrationManager - address must be different than the current address"
);
migrationManager = _newMigrationManager;
emit MigrationManagerUpdated(_newMigrationManager);
}
/// @dev Sets the address of the emergency manager.
/// @param _newEmergencyManager address The address of the new emergency manager.
function setEmergencyManager(address _newEmergencyManager)
external
onlyEmergencyManager
{
require(
_newEmergencyManager != address(0),
"StakingContract::setEmergencyManager - address must not be 0"
);
require(
emergencyManager != _newEmergencyManager,
"StakingContract::setEmergencyManager - address must be different than the current address"
);
emergencyManager = _newEmergencyManager;
emit EmergencyManagerUpdated(_newEmergencyManager);
}
/// @dev Sets the address of the stake change notifier contract.
/// @param _newNotifier IStakeChangeNotifier The address of the new stake change notifier contract.
///
/// Note: it's allowed to reset the notifier to a zero address.
function setStakeChangeNotifier(IStakeChangeNotifier _newNotifier)
external
onlyMigrationManager
{
require(
notifier != _newNotifier,
"StakingContract::setStakeChangeNotifier - address must be different than the current address"
);
notifier = _newNotifier;
emit StakeChangeNotifierUpdated(notifier);
}
/// @dev Adds a new contract to the list of approved staking contracts migration destinations.
/// @param _newStakingContract IMigratableStakingContract The new contract to add.
function addMigrationDestination(
IMigratableStakingContract _newStakingContract
) external onlyMigrationManager {
require(
address(_newStakingContract) != address(0),
"StakingContract::addMigrationDestination - address must not be 0"
);
uint256 length = approvedStakingContracts.length;
require(
length + 1 <= MAX_APPROVED_STAKING_CONTRACTS,
"StakingContract::addMigrationDestination - can't add more staking contracts"
);
// Check for duplicates.
for (uint256 i = 0; i < length; ++i) {
require(
approvedStakingContracts[i] != _newStakingContract,
"StakingContract::addMigrationDestination - can't add a duplicate staking contract"
);
}
approvedStakingContracts.push(_newStakingContract);
emit MigrationDestinationAdded(_newStakingContract);
}
/// @dev Removes a contract from the list of approved staking contracts migration destinations.
/// @param _stakingContract IMigratableStakingContract The contract to remove.
function removeMigrationDestination(
IMigratableStakingContract _stakingContract
) external onlyMigrationManager {
require(
address(_stakingContract) != address(0),
"StakingContract::removeMigrationDestination - address must not be 0"
);
// Check for existence.
(uint256 i, bool exists) = findApprovedStakingContractIndex(
_stakingContract
);
require(
exists,
"StakingContract::removeMigrationDestination - staking contract doesn't exist"
);
// Swap the requested element with the last element and then delete it using pop/
approvedStakingContracts[i] = approvedStakingContracts[approvedStakingContracts
.length - 1];
approvedStakingContracts.pop();
emit MigrationDestinationRemoved(_stakingContract);
}
/// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _amount uint256 The amount of tokens to stake.
function stake(uint256 _amount) external onlyWhenAcceptingNewStakes {
address stakeOwner = msg.sender;
uint256 totalStakedAmount = stake(stakeOwner, _amount);
emit Staked(stakeOwner, _amount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeChange(stakeOwner, _amount, true, totalStakedAmount);
}
/// @dev Unstakes $EDI tokens from msg.sender. If successful, this will start the cooldown period, after which
/// msg.sender would be able to withdraw all of his tokens.
/// @param _amount uint256 The amount of tokens to unstake.
function unstake(uint256 _amount) external {
require(
_amount > 0,
"StakingContract::unstake - amount must be greater than 0"
);
address stakeOwner = msg.sender;
Stake storage stakeData = stakes[stakeOwner];
uint256 stakedAmount = stakeData.amount;
uint256 cooldownAmount = stakeData.cooldownAmount;
uint256 cooldownEndTime = stakeData.cooldownEndTime;
require(
_amount <= stakedAmount,
"StakingContract::unstake - can't unstake more than the current stake"
);
// If any tokens in cooldown are ready for withdrawal - revert. Stake owner should withdraw their unstaked
// tokens first.
require(
cooldownAmount == 0 || cooldownEndTime > now,
"StakingContract::unstake - unable to unstake when there are tokens pending withdrawal"
);
// Update the amount of tokens in cooldown. Please note that this will also restart the cooldown period of all
// tokens in cooldown.
stakeData.amount = stakedAmount.sub(_amount);
stakeData.cooldownAmount = cooldownAmount.add(_amount);
stakeData.cooldownEndTime = now.add(cooldownPeriodInSec);
totalStakedTokens = totalStakedTokens.sub(_amount);
uint256 totalStakedAmount = stakeData.amount;
emit Unstaked(stakeOwner, _amount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeChange(stakeOwner, _amount, false, totalStakedAmount);
}
/// @dev Requests to withdraw all of staked $EDI tokens back to msg.sender. Stake owners can withdraw their $EDI
/// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was
/// requested to release all stakes).
function withdraw() external {
address stakeOwner = msg.sender;
WithdrawResult memory res = withdraw(stakeOwner);
emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount);
// Trigger staking state change notifications only if the staking amount was changed.
if (res.stakedAmountDiff == 0) {
return;
}
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeChange(stakeOwner, res.stakedAmountDiff, false, res.stakedAmount);
}
/// @dev Restakes unstaked $EDI tokens (in or after cooldown) for msg.sender.
function restake() external onlyWhenAcceptingNewStakes {
address stakeOwner = msg.sender;
Stake storage stakeData = stakes[stakeOwner];
uint256 cooldownAmount = stakeData.cooldownAmount;
require(
cooldownAmount > 0,
"StakingContract::restake - no unstaked tokens"
);
stakeData.amount = stakeData.amount.add(cooldownAmount);
stakeData.cooldownAmount = 0;
stakeData.cooldownEndTime = 0;
totalStakedTokens = totalStakedTokens.add(cooldownAmount);
uint256 totalStakedAmount = stakeData.amount;
emit Restaked(stakeOwner, cooldownAmount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeChange(stakeOwner, cooldownAmount, true, totalStakedAmount);
}
/// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least
/// the required amount using ERC20 approve.
/// @param _stakeOwner address The specified stake owner.
/// @param _amount uint256 The amount of tokens to stake.
function acceptMigration(address _stakeOwner, uint256 _amount)
external
onlyWhenAcceptingNewStakes
{
uint256 totalStakedAmount = stake(_stakeOwner, _amount);
emit AcceptedMigration(_stakeOwner, _amount, totalStakedAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeChange(_stakeOwner, _amount, true, totalStakedAmount);
}
/// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract.
/// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration.
/// @param _amount uint256 The amount of tokens to migrate.
function migrateStakedTokens(
IMigratableStakingContract _newStakingContract,
uint256 _amount
) external onlyWhenStakesNotReleased {
require(
isApprovedStakingContract(_newStakingContract),
"StakingContract::migrateStakedTokens - migration destination wasn't approved"
);
require(
_amount > 0,
"StakingContract::migrateStakedTokens - amount must be greater than 0"
);
address stakeOwner = msg.sender;
Stake storage stakeData = stakes[stakeOwner];
uint256 stakedAmount = stakeData.amount;
require(
stakedAmount > 0,
"StakingContract::migrateStakedTokens - no staked tokens"
);
require(
_amount <= stakedAmount,
"StakingContract::migrateStakedTokens - amount exceeds staked token balance"
);
stakeData.amount = stakedAmount.sub(_amount);
totalStakedTokens = totalStakedTokens.sub(_amount);
require(
_newStakingContract.getToken() == token,
"StakingContract::migrateStakedTokens - staked tokens must be the same"
);
require(
token.approve(address(_newStakingContract), _amount),
"StakingContract::migrateStakedTokens - couldn't approve transfer"
);
emit MigratedStake(stakeOwner, _amount, stakeData.amount);
_newStakingContract.acceptMigration(stakeOwner, _amount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeMigration(stakeOwner, _amount);
}
/// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method
/// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a
/// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that
/// callers will be able to batch/paginate their requests properly.
/// @param _totalAmount uint256 The total amount of rewards to distributes.
/// @param _stakeOwners address[] The addresses of the stake owners.
/// @param _amounts uint256[] The amounts of the rewards.
function distributeRewards(
uint256 _totalAmount,
address[] calldata _stakeOwners,
uint256[] calldata _amounts
) external onlyWhenAcceptingNewStakes {
require(
_totalAmount > 0,
"StakingContract::distributeRewards - total amount must be greater than 0"
);
uint256 stakeOwnersLength = _stakeOwners.length;
uint256 amountsLength = _amounts.length;
require(
stakeOwnersLength > 0 && amountsLength > 0,
"StakingContract::distributeRewards - lists can't be empty"
);
require(
stakeOwnersLength == amountsLength,
"StakingContract::distributeRewards - lists must be of the same size"
);
// Transfer all the tokens to the smart contract and update the stake owners list accordingly.
require(
token.transferFrom(msg.sender, address(this), _totalAmount),
"StakingContract::distributeRewards - insufficient allowance"
);
bool[] memory signs = new bool[](amountsLength);
uint256[] memory totalStakedAmounts = new uint256[](amountsLength);
uint256 expectedTotalAmount = 0;
for (uint256 i = 0; i < stakeOwnersLength; ++i) {
address stakeOwner = _stakeOwners[i];
uint256 amount = _amounts[i];
require(
stakeOwner != address(0),
"StakingContract::distributeRewards - stake owner can't be 0"
);
require(
amount > 0,
"StakingContract::distributeRewards - amount must be greater than 0"
);
Stake storage stakeData = stakes[stakeOwner];
stakeData.amount = stakeData.amount.add(amount);
expectedTotalAmount = expectedTotalAmount.add(amount);
uint256 totalStakedAmount = stakeData.amount;
signs[i] = true;
totalStakedAmounts[i] = totalStakedAmount;
emit Staked(stakeOwner, amount, totalStakedAmount);
}
require(
_totalAmount == expectedTotalAmount,
"StakingContract::distributeRewards - incorrect total amount"
);
totalStakedTokens = totalStakedTokens.add(_totalAmount);
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeChangeBatch(_stakeOwners, _amounts, signs, totalStakedAmounts);
}
/// @dev Returns the stake of the specified stake owner (excluding unstaked tokens).
/// @param _stakeOwner address The address to check.
/// @return uint256 The stake of the stake owner.
function getStakeBalanceOf(address _stakeOwner)
external
view
returns (uint256)
{
return stakes[_stakeOwner].amount;
}
/// @dev Returns the total amount staked tokens (excluding unstaked tokens).
/// @return uint256 The total staked tokens of all stake owners.
function getTotalStakedTokens() external view returns (uint256) {
return totalStakedTokens;
}
/// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released.
/// @param _stakeOwner address The address to check.
/// @return cooldownAmount uint256 The total tokens in cooldown.
/// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds).
function getUnstakeStatus(address _stakeOwner)
external
view
returns (uint256 cooldownAmount, uint256 cooldownEndTime)
{
Stake memory stakeData = stakes[_stakeOwner];
cooldownAmount = stakeData.cooldownAmount;
cooldownEndTime = stakeData.cooldownEndTime;
}
/// @dev Returns the address of the underlying staked token.
/// @return IERC20 The address of the token.
function getToken() external view returns (IERC20) {
return token;
}
/// @dev Requests the contract to stop accepting new staking requests.
function stopAcceptingNewStakes()
external
onlyEmergencyManager
onlyWhenAcceptingNewStakes
{
acceptingNewStakes = false;
emit StoppedAcceptingNewStake();
}
/// @dev Requests the contract to release all stakes.
function releaseAllStakes()
external
onlyEmergencyManager
onlyWhenStakesNotReleased
{
releasingAllStakes = true;
emit ReleasedAllStakes();
}
/// @dev Requests withdraw of released tokens for a list of addresses.
/// @param _stakeOwners address[] The addresses of the stake owners.
function withdrawReleasedStakes(address[] calldata _stakeOwners)
external
onlyWhenStakesReleased
{
uint256 stakeOwnersLength = _stakeOwners.length;
uint256[] memory stakedAmountDiffs = new uint256[](stakeOwnersLength);
bool[] memory signs = new bool[](stakeOwnersLength);
uint256[] memory totalStakedAmounts = new uint256[](stakeOwnersLength);
for (uint256 i = 0; i < stakeOwnersLength; ++i) {
address stakeOwner = _stakeOwners[i];
WithdrawResult memory res = withdraw(stakeOwner);
stakedAmountDiffs[i] = res.stakedAmountDiff;
signs[i] = false;
totalStakedAmounts[i] = res.stakedAmount;
emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount);
}
// Note: we aren't concerned with reentrancy since:
// 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method.
// 2. The notifier is set and managed by the migration manager.
stakeChangeBatch(
_stakeOwners,
stakedAmountDiffs,
signs,
totalStakedAmounts
);
}
/// @dev Returns whether a specific staking contract was approved as a migration destination.
/// @param _stakingContract IMigratableStakingContract The staking contract to look for.
/// @return exists bool The approval status.
function isApprovedStakingContract(
IMigratableStakingContract _stakingContract
) public view returns (bool exists) {
(, exists) = findApprovedStakingContractIndex(_stakingContract);
}
/// @dev Returns whether stake change notification is enabled.
function shouldNotifyStakeChange() internal view returns (bool) {
return address(notifier) != address(0);
}
/// @dev Notifies of stake change events.
/// @param _stakeOwner address The address of the subject stake owner.
/// @param _amount int256 The difference in the total staked amount.
/// @param _sign bool The sign of the added (true) or subtracted (false) amount.
/// @param _updatedStake uint256 The updated total staked amount.
function stakeChange(
address _stakeOwner,
uint256 _amount,
bool _sign,
uint256 _updatedStake
) internal {
if (!shouldNotifyStakeChange()) {
return;
}
notifier.stakeChange(_stakeOwner, _amount, _sign, _updatedStake);
}
/// @dev Notifies of multiple stake change events.
/// @param _stakeOwners address[] The addresses of subject stake owners.
/// @param _amounts uint256[] The differences in total staked amounts.
/// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts.
/// @param _updatedStakes uint256[] The updated total staked amounts.
function stakeChangeBatch(
address[] memory _stakeOwners,
uint256[] memory _amounts,
bool[] memory _signs,
uint256[] memory _updatedStakes
) internal {
if (!shouldNotifyStakeChange()) {
return;
}
notifier.stakeChangeBatch(
_stakeOwners,
_amounts,
_signs,
_updatedStakes
);
}
/// @dev Notifies of stake migration event.
/// @param _stakeOwner address The address of the subject stake owner.
/// @param _amount uint256 The migrated amount.
function stakeMigration(address _stakeOwner, uint256 _amount) internal {
if (!shouldNotifyStakeChange()) {
return;
}
notifier.stakeMigration(_stakeOwner, _amount);
}
/// @dev Stakes amount of $EDI tokens on behalf of the specified stake owner.
/// @param _stakeOwner address The specified stake owner.
/// @param _amount uint256 The amount of tokens to stake.
/// @return totalStakedAmount uint256 The total stake of the stake owner.
function stake(address _stakeOwner, uint256 _amount)
private
returns (uint256 totalStakedAmount)
{
require(
_stakeOwner != address(0),
"StakingContract::stake - stake owner can't be 0"
);
require(
_amount > 0,
"StakingContract::stake - amount must be greater than 0"
);
Stake storage stakeData = stakes[_stakeOwner];
stakeData.amount = stakeData.amount.add(_amount);
totalStakedTokens = totalStakedTokens.add(_amount);
totalStakedAmount = stakeData.amount;
// Transfer the tokens to the smart contract and update the stake owners list accordingly.
require(
token.transferFrom(msg.sender, address(this), _amount),
"StakingContract::stake - insufficient allowance"
);
}
/// @dev Requests to withdraw all of staked $EDI tokens back to the specified stake owner. Stake owners can withdraw
/// their $EDI tokens only after previously unstaking them and after the cooldown period has passed (unless the
/// contract was requested to release all stakes).
/// @return res WithdrawResult The result of the withdraw operation.
function withdraw(address _stakeOwner)
private
returns (WithdrawResult memory res)
{
require(
_stakeOwner != address(0),
"StakingContract::withdraw - stake owner can't be 0"
);
Stake storage stakeData = stakes[_stakeOwner];
res.stakedAmount = stakeData.amount;
res.withdrawnAmount = stakeData.cooldownAmount;
res.stakedAmountDiff = 0;
if (!releasingAllStakes) {
require(
res.withdrawnAmount > 0,
"StakingContract::withdraw - no unstaked tokens"
);
require(
stakeData.cooldownEndTime <= now,
"StakingContract::withdraw - tokens are still in cooldown"
);
} else {
// If the contract was requested to release all stakes - allow to withdraw all staked and unstaked tokens.
res.withdrawnAmount = res.withdrawnAmount.add(res.stakedAmount);
res.stakedAmountDiff = res.stakedAmount;
require(
res.withdrawnAmount > 0,
"StakingContract::withdraw - no staked or unstaked tokens"
);
stakeData.amount = 0;
totalStakedTokens = totalStakedTokens.sub(res.stakedAmount);
res.stakedAmount = 0;
}
stakeData.cooldownAmount = 0;
stakeData.cooldownEndTime = 0;
require(
token.transfer(_stakeOwner, res.withdrawnAmount),
"StakingContract::withdraw - couldn't transfer stake"
);
}
/// @dev Returns an index of an existing approved staking contract.
/// @param _stakingContract IMigratableStakingContract The staking contract to look for.
/// @return index uint The index of the located staking contract (in the case that it was found).
/// @return exists bool The search result.
function findApprovedStakingContractIndex(
IMigratableStakingContract _stakingContract
) private view returns (uint256 index, bool exists) {
uint256 length = approvedStakingContracts.length;
for (index = 0; index < length; ++index) {
if (approvedStakingContracts[index] == _stakingContract) {
exists = true;
return (index, exists);
}
}
exists = false;
}
}
| @dev Notifies of stake change events. @param _stakeOwner address The address of the subject stake owner. @param _amount int256 The difference in the total staked amount. @param _sign bool The sign of the added (true) or subtracted (false) amount. @param _updatedStake uint256 The updated total staked amount. | function stakeChange(
address _stakeOwner,
uint256 _amount,
bool _sign,
uint256 _updatedStake
) internal {
if (!shouldNotifyStakeChange()) {
return;
}
notifier.stakeChange(_stakeOwner, _amount, _sign, _updatedStake);
}
| 1,815,900 | [
1,
1248,
5032,
434,
384,
911,
2549,
2641,
18,
225,
389,
334,
911,
5541,
1758,
1021,
1758,
434,
326,
3221,
384,
911,
3410,
18,
225,
389,
8949,
509,
5034,
1021,
7114,
316,
326,
2078,
384,
9477,
3844,
18,
225,
389,
2977,
1426,
1021,
1573,
434,
326,
3096,
261,
3767,
13,
578,
10418,
329,
261,
5743,
13,
3844,
18,
225,
389,
7007,
510,
911,
2254,
5034,
1021,
3526,
2078,
384,
9477,
3844,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
384,
911,
3043,
12,
203,
3639,
1758,
389,
334,
911,
5541,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
1426,
389,
2977,
16,
203,
3639,
2254,
5034,
389,
7007,
510,
911,
203,
565,
262,
2713,
288,
203,
3639,
309,
16051,
13139,
9168,
510,
911,
3043,
10756,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
19057,
18,
334,
911,
3043,
24899,
334,
911,
5541,
16,
389,
8949,
16,
389,
2977,
16,
389,
7007,
510,
911,
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
] |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/*
* Merkle Tree Utilities for Rollup
*/
contract RollupMerkleUtils {
/* Structs */
// A partial merkle tree which can be updated with new nodes, recomputing the root
struct SparseMerkleTree {
// The root
bytes32 root;
uint height;
mapping (bytes32 => bytes32) nodes;
}
/* Fields */
// The default hashes
bytes32[160] public defaultHashes;
// A tree which is used in `update()` and `store()`
SparseMerkleTree public tree;
/**
* @notice Initialize a new SparseMerkleUtils contract, computing the default hashes for the sparse merkle tree (SMT)
*/
constructor() public {
// Calculate & set the default hashes
setDefaultHashes();
}
/* Methods */
/**
* @notice Set default hashes
*/
function setDefaultHashes() private {
// Set the initial default hash.
defaultHashes[0] = keccak256(abi.encodePacked(uint(0)));
for (uint i = 1; i < defaultHashes.length; i ++) {
defaultHashes[i] = keccak256(abi.encodePacked(defaultHashes[i-1], defaultHashes[i-1]));
}
}
/**
* @notice Get the sparse merkle root computed from some set of data blocks.
* @param _dataBlocks The data being used to generate the tree.
* @return the sparse merkle tree root
*/
function getMerkleRoot(bytes[] calldata _dataBlocks) external view returns(bytes32) {
uint nextLevelLength = _dataBlocks.length;
uint currentLevel = 0;
bytes32[] memory nodes = new bytes32[](nextLevelLength + 1); // Add one in case we have an odd number of leaves
// Generate the leaves
for (uint i = 0; i < _dataBlocks.length; i++) {
nodes[i] = keccak256(_dataBlocks[i]);
}
if (_dataBlocks.length == 1) {
return nodes[0];
}
// Add a defaultNode if we've got an odd number of leaves
if (nextLevelLength % 2 == 1) {
nodes[nextLevelLength] = defaultHashes[currentLevel];
nextLevelLength += 1;
}
// Now generate each level
while (nextLevelLength > 1) {
currentLevel += 1;
// Calculate the nodes for the currentLevel
for (uint i = 0; i < nextLevelLength / 2; i++) {
nodes[i] = getParent(nodes[i*2], nodes[i*2 + 1]);
}
nextLevelLength = nextLevelLength / 2;
// Check if we will need to add an extra node
if (nextLevelLength % 2 == 1 && nextLevelLength != 1) {
nodes[nextLevelLength] = defaultHashes[currentLevel];
nextLevelLength += 1;
}
}
// Alright! We should be left with a single node! Return it...
return nodes[0];
}
/**
* @notice Calculate root from an inclusion proof.
* @param _dataBlock The data block we're calculating root for.
* @param _path The path from the leaf to the root.
* @param _siblings The sibling nodes along the way.
* @return The next level of the tree
*/
function computeInclusionProofRoot(bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public pure returns (bytes32) {
// First compute the leaf node
bytes32 computedNode = keccak256(_dataBlock);
for (uint i = 0; i < _siblings.length; i++) {
bytes32 sibling = _siblings[i];
uint8 isComputedRightSibling = getNthBitFromRight(_path, i);
if (isComputedRightSibling == 0) {
computedNode = getParent(computedNode, sibling);
} else {
computedNode = getParent(sibling, computedNode);
}
}
// Check if the computed node (_root) is equal to the provided root
return computedNode;
}
/**
* @notice Verify an inclusion proof.
* @param _root The root of the tree we are verifying inclusion for.
* @param _dataBlock The data block we're verifying inclusion for.
* @param _path The path from the leaf to the root.
* @param _siblings The sibling nodes along the way.
* @return The next level of the tree
*/
function verify(bytes32 _root, bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public pure returns (bool) {
// First compute the leaf node
bytes32 calculatedRoot = computeInclusionProofRoot(
_dataBlock,
_path,
_siblings
);
return calculatedRoot == _root;
}
/**
* @notice Update the stored tree / root with a particular dataBlock at some path (no siblings needed)
* @param _dataBlock The data block we're storing/verifying
* @param _path The path from the leaf to the root / the index of the leaf.
*/
function update(bytes memory _dataBlock, uint _path) public {
bytes32[] memory siblings = getSiblings(_path);
store(_dataBlock, _path, siblings);
}
/**
* @notice Update the stored tree / root with a particular leaf hash at some path (no siblings needed)
* @param _leaf The leaf we're storing/verifying
* @param _path The path from the leaf to the root / the index of the leaf.
*/
function updateLeaf(bytes32 _leaf, uint _path) public {
bytes32[] memory siblings = getSiblings(_path);
storeLeaf(_leaf, _path, siblings);
}
/**
* @notice Store a particular merkle proof & verify that the root did not change.
* @param _dataBlock The data block we're storing/verifying
* @param _path The path from the leaf to the root / the index of the leaf.
* @param _siblings The sibling nodes along the way.
*/
function verifyAndStore(bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public {
bytes32 oldRoot = tree.root;
store(_dataBlock, _path, _siblings);
require(tree.root == oldRoot, "Failed same root verification check! This was an inclusion proof for a different tree!");
}
/**
* @notice Store a particular dataBlock & its intermediate nodes in the tree
* @param _dataBlock The data block we're storing.
* @param _path The path from the leaf to the root / the index of the leaf.
* @param _siblings The sibling nodes along the way.
*/
function store(bytes memory _dataBlock, uint _path, bytes32[] memory _siblings) public {
// Compute the leaf node & store the leaf
bytes32 leaf = keccak256(_dataBlock);
storeLeaf(leaf, _path, _siblings);
}
/**
* @notice Store a particular leaf hash & its intermediate nodes in the tree
* @param _leaf The leaf we're storing.
* @param _path The path from the leaf to the root / the index of the leaf.
* @param _siblings The sibling nodes along the way.
*/
function storeLeaf(bytes32 _leaf, uint _path, bytes32[] memory _siblings) public {
// First compute the leaf node
bytes32 computedNode = _leaf;
for (uint i = 0; i < _siblings.length; i++) {
bytes32 parent;
bytes32 sibling = _siblings[i];
uint8 isComputedRightSibling = getNthBitFromRight(_path, i);
if (isComputedRightSibling == 0) {
parent = getParent(computedNode, sibling);
// Store the node!
storeNode(parent, computedNode, sibling);
} else {
parent = getParent(sibling, computedNode);
// Store the node!
storeNode(parent, sibling, computedNode);
}
computedNode = parent;
}
// Store the new root
tree.root = computedNode;
}
/**
* @notice Get siblings for a leaf at a particular index of the tree.
* This is used for updates which don't include sibling nodes.
* @param _path The path from the leaf to the root / the index of the leaf.
* @return The sibling nodes along the way.
*/
function getSiblings(uint _path) public view returns (bytes32[] memory) {
bytes32[] memory siblings = new bytes32[](tree.height);
bytes32 computedNode = tree.root;
for(uint i = tree.height; i > 0; i--) {
uint siblingIndex = i-1;
(bytes32 leftChild, bytes32 rightChild) = getChildren(computedNode);
if (getNthBitFromRight(_path, siblingIndex) == 0) {
computedNode = leftChild;
siblings[siblingIndex] = rightChild;
} else {
computedNode = rightChild;
siblings[siblingIndex] = leftChild;
}
}
// Now store everything
return siblings;
}
/*********************
* Utility Functions *
********************/
/**
* @notice Get our stored tree's root
* @return The merkle root of the tree
*/
function getRoot() public view returns(bytes32) {
return tree.root;
}
/**
* @notice Set the tree root and height of the stored tree
* @param _root The merkle root of the tree
* @param _height The height of the tree
*/
function setMerkleRootAndHeight(bytes32 _root, uint _height) public {
tree.root = _root;
tree.height = _height;
}
/**
* @notice Store node in the (in-storage) sparse merkle tree
* @param _parent The parent node
* @param _leftChild The left child of the parent in the tree
* @param _rightChild The right child of the parent in the tree
*/
function storeNode(bytes32 _parent, bytes32 _leftChild, bytes32 _rightChild) public {
tree.nodes[getLeftSiblingKey(_parent)] = _leftChild;
tree.nodes[getRightSiblingKey(_parent)] = _rightChild;
}
/**
* @notice Get the parent of two children nodes in the tree
* @param _left The left child
* @param _right The right child
* @return The parent node
*/
function getParent(bytes32 _left, bytes32 _right) internal pure returns(bytes32) {
return keccak256(abi.encodePacked(_left, _right));
}
/**
* @notice get the n'th bit in a uint.
* For instance, if exampleUint=binary(11), getNth(exampleUint, 0) == 1, getNth(2, 1) == 1
* @param _intVal The uint we are extracting a bit out of
* @param _index The index of the bit we want to extract
* @return The bit (1 or 0) in a uint8
*/
function getNthBitFromRight(uint _intVal, uint _index) public pure returns (uint8) {
return uint8(_intVal >> _index & 1);
}
/**
* @notice Get the children of some parent in the tree
* @param _parent The parent node
* @return (rightChild, leftChild) -- the two children of the parent
*/
function getChildren(bytes32 _parent) public view returns(bytes32, bytes32) {
return (tree.nodes[getLeftSiblingKey(_parent)], tree.nodes[getRightSiblingKey(_parent)]);
}
/**
* @notice Get the right sibling key. Note that these keys overwrite the first bit of the hash
to signify if it is on the right side of the parent or on the left
* @param _parent The parent node
* @return the key for the left sibling (0 as the first bit)
*/
function getLeftSiblingKey(bytes32 _parent) public pure returns(bytes32) {
return _parent & 0x0111111111111111111111111111111111111111111111111111111111111111;
}
/**
* @notice Get the right sibling key. Note that these keys overwrite the first bit of the hash
to signify if it is on the right side of the parent or on the left
* @param _parent The parent node
* @return the key for the right sibling (1 as the first bit)
*/
function getRightSiblingKey(bytes32 _parent) public pure returns(bytes32) {
return _parent | 0x1000000000000000000000000000000000000000000000000000000000000000;
}
}
| Check if the computed node (_root) is equal to the provided root | return computedNode;
| 5,448,920 | [
1,
1564,
309,
326,
8470,
756,
261,
67,
3085,
13,
353,
3959,
358,
326,
2112,
1365,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
327,
8470,
907,
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,
-100
] |
./full_match/1/0x6aD5f5A36733DCEfb3c5Cb9e09FDEc734ED8E339/sources/src/Token.sol | cant overflow because: MAX_BUY_ON_END > MAX_BUY_ON_START MAX_BUY_END_TIME >= block.timestamp all numbers are small enough for type(uint256).max | function _revertOnMaxBuyExceeded(uint256 newAmount) internal view {
if (block.timestamp > MAX_BUY_DISABLED_TIME) {
return;
}
if (block.timestamp > MAX_BUY_END_TIME) {
if (newAmount > MAX_BUY_ON_END) revert MaxBuyExceeded(MAX_BUY_ON_END, newAmount);
}
unchecked {
uint256 maxBuyAmount = MAX_BUY_ON_END
- (MAX_BUY_END_TIME - block.timestamp) * (MAX_BUY_ON_END - MAX_BUY_ON_START) / MAX_BUY_DURATION;
if (maxBuyAmount < newAmount) revert MaxBuyExceeded(maxBuyAmount, newAmount);
}
}
| 3,844,626 | [
1,
71,
970,
9391,
2724,
30,
4552,
67,
3000,
61,
67,
673,
67,
4415,
405,
4552,
67,
3000,
61,
67,
673,
67,
7570,
4552,
67,
3000,
61,
67,
4415,
67,
4684,
1545,
1203,
18,
5508,
777,
5600,
854,
5264,
7304,
364,
618,
12,
11890,
5034,
2934,
1896,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
266,
1097,
1398,
2747,
38,
9835,
10069,
12,
11890,
5034,
394,
6275,
13,
2713,
1476,
288,
203,
3639,
309,
261,
2629,
18,
5508,
405,
4552,
67,
3000,
61,
67,
24493,
67,
4684,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
2629,
18,
5508,
405,
4552,
67,
3000,
61,
67,
4415,
67,
4684,
13,
288,
203,
5411,
309,
261,
2704,
6275,
405,
4552,
67,
3000,
61,
67,
673,
67,
4415,
13,
15226,
4238,
38,
9835,
10069,
12,
6694,
67,
3000,
61,
67,
673,
67,
4415,
16,
394,
6275,
1769,
203,
3639,
289,
203,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
943,
38,
9835,
6275,
273,
4552,
67,
3000,
61,
67,
673,
67,
4415,
203,
7734,
300,
261,
6694,
67,
3000,
61,
67,
4415,
67,
4684,
300,
1203,
18,
5508,
13,
380,
261,
6694,
67,
3000,
61,
67,
673,
67,
4415,
300,
4552,
67,
3000,
61,
67,
673,
67,
7570,
13,
342,
4552,
67,
3000,
61,
67,
24951,
31,
203,
203,
5411,
309,
261,
1896,
38,
9835,
6275,
411,
394,
6275,
13,
15226,
4238,
38,
9835,
10069,
12,
1896,
38,
9835,
6275,
16,
394,
6275,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
struct FullAbsoluteTokenAmount {
AbsoluteTokenAmountMeta base;
AbsoluteTokenAmountMeta[] underlying;
}
struct AbsoluteTokenAmountMeta {
AbsoluteTokenAmount absoluteTokenAmount;
ERC20Metadata erc20metadata;
}
struct ERC20Metadata {
string name;
string symbol;
uint8 decimals;
}
struct AdapterBalance {
bytes32 protocolAdapterName;
AbsoluteTokenAmount[] absoluteTokenAmounts;
}
struct AbsoluteTokenAmount {
address token;
uint256 amount;
}
struct Component {
address token;
uint256 rate;
}
struct TransactionData {
Action[] actions;
TokenAmount[] inputs;
Fee fee;
AbsoluteTokenAmount[] requiredOutputs;
uint256 nonce;
}
struct Action {
bytes32 protocolAdapterName;
ActionType actionType;
TokenAmount[] tokenAmounts;
bytes data;
}
struct TokenAmount {
address token;
uint256 amount;
AmountType amountType;
}
struct Fee {
uint256 share;
address beneficiary;
}
enum ActionType { None, Deposit, Withdraw }
enum AmountType { None, Relative, Absolute }
abstract contract ProtocolAdapter {
/**
* @dev MUST return amount and type of the given token
* locked on the protocol by the given account.
*/
function getBalance(
address token,
address account
)
public
view
virtual
returns (uint256);
}
contract UniswapExchangeAdapter is ProtocolAdapter {
/**
* @notice This function is unavailable for exchange adapter.
* @dev Implementation of ProtocolAdapter abstract contract function.
*/
function getBalance(
address,
address
)
public
view
override
returns (uint256)
{
revert("UEA: no balance");
}
}
abstract contract InteractiveAdapter is ProtocolAdapter {
uint256 internal constant DELIMITER = 1e18;
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
* @dev The function must deposit assets to the protocol.
* @return MUST return assets to be sent back to the `msg.sender`.
*/
function deposit(
TokenAmount[] memory tokenAmounts,
bytes memory data
)
public
payable
virtual
returns (address[] memory);
/**
* @dev The function must withdraw assets from the protocol.
* @return MUST return assets to be sent back to the `msg.sender`.
*/
function withdraw(
TokenAmount[] memory tokenAmounts,
bytes memory data
)
public
payable
virtual
returns (address[] memory);
function getAbsoluteAmountDeposit(
TokenAmount memory tokenAmount
)
internal
view
virtual
returns (uint256)
{
address token = tokenAmount.token;
uint256 amount = tokenAmount.amount;
AmountType amountType = tokenAmount.amountType;
require(
amountType == AmountType.Relative || amountType == AmountType.Absolute,
"IA: bad amount type"
);
if (amountType == AmountType.Relative) {
require(amount <= DELIMITER, "IA: bad amount");
uint256 balance;
if (token == ETH) {
balance = address(this).balance;
} else {
balance = ERC20(token).balanceOf(address(this));
}
if (amount == DELIMITER) {
return balance;
} else {
return mul(balance, amount) / DELIMITER;
}
} else {
return amount;
}
}
function getAbsoluteAmountWithdraw(
TokenAmount memory tokenAmount
)
internal
view
virtual
returns (uint256)
{
address token = tokenAmount.token;
uint256 amount = tokenAmount.amount;
AmountType amountType = tokenAmount.amountType;
require(
amountType == AmountType.Relative || amountType == AmountType.Absolute,
"IA: bad amount type"
);
if (amountType == AmountType.Relative) {
require(amount <= DELIMITER, "IA: bad amount");
uint256 balance = getBalance(token, address(this));
if (amount == DELIMITER) {
return balance;
} else {
return mul(balance, amount) / DELIMITER;
}
} else {
return amount;
}
}
function mul(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "IA: mul overflow");
return c;
}
}
interface UniswapV2Router01 {
function swapExactTokensForTokens(
uint,
uint,
address[] calldata,
address,
uint
) external returns (uint[] memory);
function swapTokensForExactTokens(
uint,
uint,
address[] calldata,
address,
uint
) external returns (uint[] memory);
}
contract UniswapV2ExchangeInteractiveAdapter is InteractiveAdapter, UniswapExchangeAdapter {
using SafeERC20 for ERC20;
address internal constant ROUTER = 0xf164fC0Ec4E93095b804a4795bBe1e041497b92a;
/**
* @notice Exchange tokens using Uniswap pool.
* @param tokenAmounts Array with one element - TokenAmount struct with
* "from" token address, "from" token amount, and amount type.
* @param data Uniswap exchange path starting from tokens[0] (ABI-encoded).
* @return tokensToBeWithdrawn Array with one element - token address to be exchanged to.
* @dev Implementation of InteractiveAdapter function.
*/
function deposit(
TokenAmount[] memory tokenAmounts,
bytes memory data
)
public
payable
override
returns (address[] memory tokensToBeWithdrawn)
{
require(tokenAmounts.length == 1, "UEIA: should be 1 tokenAmount");
address[] memory path = abi.decode(data, (address[]));
address token = tokenAmounts[0].token;
require(token == path[0], "UEIA: bad path[0]");
uint256 amount = getAbsoluteAmountDeposit(tokenAmounts[0]);
tokensToBeWithdrawn = new address[](1);
tokensToBeWithdrawn[0] = path[path.length - 1];
ERC20(token).safeApprove(ROUTER, amount, "UEIA[1]");
try UniswapV2Router01(ROUTER).swapExactTokensForTokens(
amount,
0,
path,
address(this),
// solhint-disable-next-line not-rely-on-time
now
) returns (uint256[] memory) { // solhint-disable-line no-empty-blocks
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("UEIA: deposit fail");
}
}
/**
* @notice Exchange tokens using Uniswap pool.
* @param tokenAmounts Array with one element - TokenAmount struct with
* "to" token address, "to" token amount, and amount type (must be absolute).
* @param data Uniswap exchange path ending with tokens[0] (ABI-encoded).
* @return tokensToBeWithdrawn Array with one element - token address to be changed to.
* @dev Implementation of InteractiveAdapter function.
*/
function withdraw(
TokenAmount[] memory tokenAmounts,
bytes memory data
)
public
payable
override
returns (address[] memory tokensToBeWithdrawn)
{
require(tokenAmounts.length == 1, "UEIA: should be 1 tokenAmount");
require(tokenAmounts[0].amountType == AmountType.Absolute, "UEIA: bad type");
address[] memory path = abi.decode(data, (address[]));
address token = tokenAmounts[0].token;
require(token == path[path.length - 1], "UEIA: bad path[path.length - 1]");
uint256 amount = tokenAmounts[0].amount;
tokensToBeWithdrawn = new address[](1);
tokensToBeWithdrawn[0] = token;
ERC20(path[0]).safeApprove(ROUTER, ERC20(path[0]).balanceOf(address(this)), "UEIA[2]");
try UniswapV2Router01(ROUTER).swapTokensForExactTokens(
amount,
type(uint256).max,
path,
address(this),
// solhint-disable-next-line not-rely-on-time
now
) returns (uint256[] memory) { //solhint-disable-line no-empty-blocks
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("UEIA: withdraw fail");
}
ERC20(path[0]).safeApprove(ROUTER, 0, "UEIA[3]");
}
}
interface ERC20 {
function approve(address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address) external view returns (uint256);
function allowance(address, address) external view returns (uint256);
}
library SafeERC20 {
function safeTransfer(
ERC20 token,
address to,
uint256 value,
string memory location
)
internal
{
callOptionalReturn(
token,
abi.encodeWithSelector(
token.transfer.selector,
to,
value
),
"transfer",
location
);
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value,
string memory location
)
internal
{
callOptionalReturn(
token,
abi.encodeWithSelector(
token.transferFrom.selector,
from,
to,
value
),
"transferFrom",
location
);
}
function safeApprove(
ERC20 token,
address spender,
uint256 value,
string memory location
)
internal
{
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: bad approve call"
);
callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
value
),
"approve",
location
);
}
/**
* @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).
* @param location Location of the call (for debug).
*/
function callOptionalReturn(
ERC20 token,
bytes memory data,
string memory functionName,
string memory location
)
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 implement two-steps call as callee is a contract is a responsibility of a caller.
// 1. The call itself is made, and success asserted
// 2. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(
success,
string(
abi.encodePacked(
"SafeERC20: ",
functionName,
" failed in ",
location
)
)
);
if (returndata.length > 0) { // Return data is optional
require(
abi.decode(returndata, (bool)),
string(
abi.encodePacked(
"SafeERC20: ",
functionName,
" returned false in ",
location
)
)
);
}
}
}
| solhint-disable-line no-empty-blocks
| ) returns (uint256[] memory) { | 7,473,294 | [
1,
18281,
11317,
17,
8394,
17,
1369,
1158,
17,
5531,
17,
7996,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
262,
1135,
261,
11890,
5034,
8526,
3778,
13,
288,
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
] |
pragma solidity ^0.4.15;
contract Token {
/// @return total amount of tokens
// function totalSupply() public constant returns (uint supply);
// `totalSupply` is defined below because the automatically generated
// getter function does not match the abstract function above
uint public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract StandardToken is Token {
function transfer(address _to, uint _value) public returns (bool success) {
if (balances[msg.sender] >= _value && // Account has sufficient balance
balances[_to] + _value >= balances[_to]) { // Overflow check
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { throw; }
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
if (balances[_from] >= _value && // Account has sufficient balance
allowed[_from][msg.sender] >= _value && // Amount has been approved
balances[_to] + _value >= balances[_to]) { // Overflow check
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
} else { throw; }
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
}
// Based on TokenFactory(https://github.com/ConsenSys/Token-Factory)
contract SnipCoin is StandardToken {
string public constant name = "SnipCoin"; // Token name
string public symbol = "SNIP"; // Token identifier
uint8 public constant decimals = 18; // Decimal points for token
uint public totalEthReceivedInWei; // The total amount of Ether received during the sale in WEI
uint public totalUsdReceived; // The total amount of Ether received during the sale in USD terms
uint public totalUsdValueOfAllTokens; // The total USD value of 100% of tokens
string public version = "1.0"; // Code version
address public saleWalletAddress; // The wallet address where the Ether from the sale will be stored
mapping (address => bool) public uncappedBuyerList; // The list of buyers allowed to participate in the sale without a cap
mapping (address => uint) public cappedBuyerList; // The list of buyers allowed to participate in the sale, with their updated payment sum
uint public snipCoinToEtherExchangeRate = 76250; // This is the ratio of SnipCoin to Ether, could be updated by the owner, change before the sale
bool public isSaleOpen = false; // This opens and closes upon external command
bool public transferable = false; // Tokens are transferable
uint public ethToUsdExchangeRate = 282; // Number of USD in one Eth
address public contractOwner; // Address of the contract owner
// Address of an additional account to manage the sale without risk to the tokens or eth. Change before the sale
address public accountWithUpdatePermissions = 0x6933784a82F5daDEbB600Bed8670667837aD196f;
uint public constant PERCENTAGE_OF_TOKENS_SOLD_IN_SALE = 28; // Percentage of all the tokens being sold in the current sale
uint public constant DECIMALS_MULTIPLIER = 10**uint(decimals); // Multiplier for the decimals
uint public constant SALE_CAP_IN_USD = 8000000; // The total sale cap in USD
uint public constant MINIMUM_PURCHASE_IN_USD = 50; // It is impossible to purchase tokens for more than $50 in the sale.
uint public constant USD_PURCHASE_AMOUNT_REQUIRING_ID = 4500; // Above this purchase amount an ID is required.
modifier onlyPermissioned() {
require((msg.sender == contractOwner) || (msg.sender == accountWithUpdatePermissions));
_;
}
modifier verifySaleNotOver() {
require(isSaleOpen);
require(totalUsdReceived < SALE_CAP_IN_USD); // Make sure that sale isn't over
_;
}
modifier verifyBuyerCanMakePurchase() {
uint currentPurchaseValueInUSD = uint(msg.value / getWeiToUsdExchangeRate()); // The USD worth of tokens sold
uint totalPurchaseIncludingCurrentPayment = currentPurchaseValueInUSD + cappedBuyerList[msg.sender]; // The USD worth of all tokens this buyer bought
require(currentPurchaseValueInUSD > MINIMUM_PURCHASE_IN_USD); // Minimum transfer is of $50
uint EFFECTIVE_MAX_CAP = SALE_CAP_IN_USD + 1000; // This allows for the end of the sale by passing $8M and reaching the cap
require(EFFECTIVE_MAX_CAP - totalUsdReceived > currentPurchaseValueInUSD); // Make sure that there is enough usd left to buy.
if (!uncappedBuyerList[msg.sender]) // If buyer is on uncapped white list then no worries, else need to make sure that they're okay
{
require(cappedBuyerList[msg.sender] > 0); // Check that the sender has been initialized.
require(totalPurchaseIncludingCurrentPayment < USD_PURCHASE_AMOUNT_REQUIRING_ID); // Check that they're not buying too much
}
_;
}
function SnipCoin() public {
initializeSaleWalletAddress();
initializeEthReceived();
initializeUsdReceived();
contractOwner = msg.sender; // The creator of the contract is its owner
totalSupply = 10000000000 * DECIMALS_MULTIPLIER; // In total, 10 billion tokens
balances[contractOwner] = totalSupply; // Initially give owner all of the tokens
Transfer(0x0, contractOwner, totalSupply);
}
function initializeSaleWalletAddress() internal {
saleWalletAddress = 0xb4Ad56E564aAb5409fe8e34637c33A6d3F2a0038; // Change before the sale
}
function initializeEthReceived() internal {
totalEthReceivedInWei = 14018 * 1 ether; // Ether received before public sale. Verify this figure before the sale starts.
}
function initializeUsdReceived() internal {
totalUsdReceived = 3953076; // USD received before public sale. Verify this figure before the sale starts.
totalUsdValueOfAllTokens = totalUsdReceived * 100 / PERCENTAGE_OF_TOKENS_SOLD_IN_SALE; // sold tokens are 28% of all tokens
}
function getWeiToUsdExchangeRate() public constant returns(uint) {
return 1 ether / ethToUsdExchangeRate; // Returns how much Wei one USD is worth
}
function updateEthToUsdExchangeRate(uint newEthToUsdExchangeRate) public onlyPermissioned {
ethToUsdExchangeRate = newEthToUsdExchangeRate; // Change exchange rate to new value, influences the counter of when the sale is over.
}
function updateSnipCoinToEtherExchangeRate(uint newSnipCoinToEtherExchangeRate) public onlyPermissioned {
snipCoinToEtherExchangeRate = newSnipCoinToEtherExchangeRate; // Change the exchange rate to new value, influences tokens received per purchase
}
function openOrCloseSale(bool saleCondition) public onlyPermissioned {
require(!transferable);
isSaleOpen = saleCondition; // Decide if the sale should be open or closed (default: closed)
}
function allowTransfers() public onlyPermissioned {
require(!isSaleOpen);
transferable = true;
}
function addAddressToCappedAddresses(address addr) public onlyPermissioned {
cappedBuyerList[addr] = 1; // Allow a certain address to purchase SnipCoin up to the cap (<4500)
}
function addMultipleAddressesToCappedAddresses(address[] addrList) public onlyPermissioned {
for (uint i = 0; i < addrList.length; i++) {
addAddressToCappedAddresses(addrList[i]); // Allow a certain address to purchase SnipCoin up to the cap (<4500)
}
}
function addAddressToUncappedAddresses(address addr) public onlyPermissioned {
uncappedBuyerList[addr] = true; // Allow a certain address to purchase SnipCoin above the cap (>=$4500)
}
function addMultipleAddressesToUncappedAddresses(address[] addrList) public onlyPermissioned {
for (uint i = 0; i < addrList.length; i++) {
addAddressToUncappedAddresses(addrList[i]); // Allow a certain address to purchase SnipCoin up to the cap (<4500)
}
}
function transfer(address _to, uint _value) public returns (bool success) {
require(transferable);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(transferable);
return super.transferFrom(_from, _to, _value);
}
function () public payable verifySaleNotOver verifyBuyerCanMakePurchase {
uint tokens = snipCoinToEtherExchangeRate * msg.value;
balances[contractOwner] -= tokens;
balances[msg.sender] += tokens;
Transfer(contractOwner, msg.sender, tokens);
totalEthReceivedInWei = totalEthReceivedInWei + msg.value; // total eth received counter
uint usdReceivedInCurrentTransaction = uint(msg.value / getWeiToUsdExchangeRate());
totalUsdReceived = totalUsdReceived + usdReceivedInCurrentTransaction; // total usd received counter
totalUsdValueOfAllTokens = totalUsdReceived * 100 / PERCENTAGE_OF_TOKENS_SOLD_IN_SALE; // sold tokens are 28% of all tokens
if (cappedBuyerList[msg.sender] > 0)
{
cappedBuyerList[msg.sender] = cappedBuyerList[msg.sender] + usdReceivedInCurrentTransaction;
}
saleWalletAddress.transfer(msg.value); // Transfer ether to safe sale address
}
} | Change exchange rate to new value, influences the counter of when the sale is over.
| ethToUsdExchangeRate = newEthToUsdExchangeRate; | 12,977,093 | [
1,
3043,
7829,
4993,
358,
394,
460,
16,
13947,
89,
2369,
326,
3895,
434,
1347,
326,
272,
5349,
353,
1879,
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
] | [
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,
3639,
13750,
774,
3477,
72,
11688,
4727,
273,
394,
41,
451,
774,
3477,
72,
11688,
4727,
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
] |
// contracts/Pandas.sol
// SPDX-License-Identifier: MIT
// ~Forked from Anonymice~
pragma solidity ^0.8.0;
import "./ERC721Enumerable.sol";
import "./IShoots.sol";
import "./PandaLibrary.sol";
import "hardhat/console.sol";
contract Panda is ERC721Enumerable {
using PandaLibrary for uint8;
struct Trait {
string traitName;
string traitType;
string pixels;
uint256 pixelCount;
}
//Mappings
mapping(uint256 => Trait[]) public traitTypes;
mapping(string => bool) hashToMinted;
mapping(uint256 => string) internal tokenIdToHash;
mapping (uint => string) internal specials;
//uint256s
uint256 MAX_SUPPLY = 10000;
uint256 INITIAL_MINTS = 3000;
uint256 SEED_NONCE = 0;
uint256 WALLET_LIMIT = 4;
//string arrays
string[] LETTERS = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z"
];
//uint arrays
uint16[][8] TIERS;
//address
address ShootsAddress;
address _owner;
//bool
bool mintEnabled;
constructor() ERC721("Bamboozlers", "Bamboozlers") {
_owner = msg.sender;
//Declare all the rarity tiers
//headwear
TIERS[0] = [3040, 1750, 1750, 1750, 500, 500, 500, 200, 10];
//eyes
TIERS[1] = [3790, 1750, 1750, 500, 500, 500, 500, 500, 200, 10];
//mouth
TIERS[2] = [3140, 1750, 1750, 1750, 500, 500, 200, 200, 200, 10];
//ears
TIERS[3] = [7800, 1750, 500];
//torso
TIERS[4] = [4090, 1750, 1750, 500, 500, 500, 500, 200, 200, 10];
//head
TIERS[5] = [7800, 1750, 500];
//body
TIERS[6] = [3330, 3330, 3330, 10];
//bg
TIERS[7] = [5940, 1750, 500, 500, 500, 200, 200, 200, 200, 10];
//Rave
specials [6] = '<path fill="#fff" fill-opacity="0" stroke-width="0" d="M0 0h24v24H0z"><animate attributeType="XML" attributeName="fill-opacity" values="0;.1;.2;.3;.4;.5;.01" dur="7s" repeatCount="1"/> <animate attributeName="fill" attributeType="XML" values="#45b6fe;white;cyan" keyTimes= "0; 0.8; 1" dur="0.72s" repeatCount="indefinite"/></path>';
//Vampire
specials [7] = '<path fill="RED" fill-opacity="0" stroke-width="0" d="M0 0h24v24H0z"><animate attributeType="XML" attributeName="fill-opacity" values="0;0;0;0.05;0.13;0.2;0;0.12;0.08;0;0;0" dur="0.6s" repeatCount="6"/></path>';
//Hypno
specials [5] = '<animateTransform attributeName="transform" type="rotate" from="0 0 0" to="360 0 0" dur="3s" repeatCount="2" additive="sum"/>';
specials [10] = '<circle r="35" class="c48" x="12" y="12"/>';
//space
specials [8] = '<animateTransform attributeName="transform" type="scale" keyTimes="0;0.25;0.5;0.75;1" values="0;0.35;0.1.28;0.75.9;1" dur="1.5s" additive="sum" transform-origin="50% 50%" />';
//Panda Patrol
specials [11] ='<path fill="#fff" fill-opacity="0" stroke-width="0" d="M0 0h24v24H0z"><animate attributeType="XML" attributeName="fill-opacity" values="0.03;.3;.2;.3;.25;.3;.3;.3;0.25;0.05;0.001" dur="2s" repeatCount="2"/> <animate attributeName="fill" attributeType="XML" values="red;blue;red" keyTimes= "0; 0.6; 1" dur="0.4s" repeatCount="indefinite"/></path>';
// Toad
specials [12] = '<g class="c28"><rect x="11" y="14"/><rect x="12" y="14"/><rect x="13" y="14"/><rect x="14" y="16"/><rect x="11" y="15"/><rect x="11" y="15"/><rect x="13" y="15"/><rect x="10" y="16"/></g><g class="c28"><rect x="11" y="16"/><rect x="13" y="16"/> <animate attributeName="display" values="inline;none;inline;none;none" keyTimes="0;0.25;0.5;0.75;1" dur="1s" repeatCount="indefinite"/></g><g class="c28"><rect x="10" y="15"/><rect x="13" y="16"/> <animate attributeName="display" values="none;inline;none;none;none" keyTimes="0;0.25;0.5;0.75;1" dur="1s" repeatCount="indefinite"/></g><g class="c28"><rect x="11" y="16"/><rect x="14" y="15"/> <animate attributeName="display" values="none;none;none;inline;none" keyTimes="0;0.25;0.5;0.75;1" dur="1s" repeatCount="indefinite"/></g>';
}
/*
__ __ _ _ _ ___ _ _
| \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___
| |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-<
|_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/
|___/
*/
/**
* @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier.
* @param _randinput The input from 0 - 10000 to use for rarity gen.
* @param _rarityTier The tier to use.
*/
function rarityGen(uint256 _randinput, uint8 _rarityTier)
internal
view
returns (string memory)
{
uint16 currentLowerBound = 0;
for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) {
uint16 thisPercentage = TIERS[_rarityTier][i];
if (
_randinput >= currentLowerBound &&
_randinput < currentLowerBound + thisPercentage
) return i.toString();
currentLowerBound = currentLowerBound + thisPercentage;
}
revert();
}
/**
* @dev Generates a 9 digit hash from a tokenId, address, and random number.
* @param _t The token id to be used within the hash.
* @param _a The address to be used within the hash.
* @param _c The custom nonce to be used within the hash.
*/
function hash(
uint256 _t,
address _a,
uint256 _c
) internal returns (string memory) {
require(_c < 10);
// This will generate a 9 character string.
//The last 8 digits are random, the first is 0, due to the panda not being burned.
string memory currentHash = "0";
for (uint8 i = 0; i < 8; i++) {
SEED_NONCE++;
uint16 _randinput = uint16(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_t,
_a,
_c,
SEED_NONCE
)
)
) % 10000
);
currentHash = string(
abi.encodePacked(currentHash, rarityGen(_randinput, i))
);
}
if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1);
return currentHash;
}
/**
* @dev Returns the current Shoots cost of minting.
*/
function currentShootsCost() public view returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply <= INITIAL_MINTS) return 0;
if (_totalSupply > INITIAL_MINTS && _totalSupply <= 5000)
return 100 ether;
if (_totalSupply > 5000 && _totalSupply <= 7000)
return 500 ether;
if (_totalSupply > 7000 && _totalSupply <= 9000)
return 1000 ether;
if (_totalSupply > 9000 && _totalSupply <= 10000)
return 2000 ether;
revert();
}
/**
* @dev Mint internal, this is to avoid code duplication.
*/
function mintInternal(address mintTo) internal {
uint256 _totalSupply = totalSupply();
require(_totalSupply < MAX_SUPPLY);
require(!PandaLibrary.isContract(msg.sender));
uint256 thisTokenId = _totalSupply;
tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0);
hashToMinted[tokenIdToHash[thisTokenId]] = true;
_mint(mintTo, thisTokenId);
}
/**
* @dev Mints new tokens.
* No minting is permitted during the initial mint if WALLET_LIMIT is met.
*/
function getBamboozled() public {
require (mintEnabled);
if (totalSupply() < INITIAL_MINTS)
{
require (balanceOf(msg.sender)<WALLET_LIMIT, "Wallet limit reached");
return mintInternal(msg.sender);
}
//Burn this much Shoots
IShoots(ShootsAddress).burnFrom(msg.sender, currentShootsCost());
return mintInternal(msg.sender);
}
/**
* @dev Dev team mint tokens.
* disables automatically once dev mint cap is met and enables public mint
*/
function devTeamMint(address mintTo) public onlyOwner
{
require (!mintEnabled);
if (totalSupply() == 99) mintEnabled=true;
return mintInternal(mintTo);
}
/**
* @dev Burns and mints new.
* @param _tokenId The token to burn.
*/
function burnForMint(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
//Burn token
_transfer(
msg.sender,
0x000000000000000000000000000000000000dEaD,
_tokenId
);
mintInternal(msg.sender);
}
/*
____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____
| \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/
| D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_
| / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ |
| . \| || | || | | | | || | \ | | | | || || | |\ |
|__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Helper function to reduce pixel size within contract
*/
function letterToNumber(string memory _inputLetter)
internal
view
returns (uint8)
{
for (uint8 i = 0; i < LETTERS.length; i++) {
if (
keccak256(abi.encodePacked((LETTERS[i]))) ==
keccak256(abi.encodePacked((_inputLetter)))
) return (i); //modified from original to permit full frame art
}
revert();
}
/**
* @dev Hash to SVG function
*/
function hashToSVG(string memory _hash)
public
view
returns (string memory)
{
string memory svgString;
bool[24][24] memory placedPixels;
uint bg;
bool use_pp;
bool use_toad;
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = PandaLibrary.parseInt(
PandaLibrary.substring(_hash, i, i + 1)
);
//* @dev: Additions to Anonymice to handle animation SVG strings
if (i==1 && thisTraitIndex==8) use_pp=true;
if (i==8) bg = thisTraitIndex;
if (i==3 && thisTraitIndex==8) use_toad=true;
//* @dev: Additions to Anonymice to handle animation SVG strings alternate decoding method implemented for full-image backgrounds (trait type 8)
// XY coordinates removed to save gas; assumes all 576 pixels are filled. Pixels iterate down then across ((0,0), (0,1), (0,2)...)
if (i==8){
uint8 y;
uint8 x;
for (
uint16 j = 0;
j < traitTypes[i][thisTraitIndex].pixelCount;
j++
) {
if (y==24){
x++;
y=0;
}
string memory thisPixel = PandaLibrary.substring(
traitTypes[i][thisTraitIndex].pixels,
j * 2,
j * 2 + 2
);
if (placedPixels[x][y]){
y ++;
continue;
}
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
PandaLibrary.substring(thisPixel, 0, 2),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
placedPixels[x][y] = true;
y++;
}
}
else
{
for (
uint16 j = 0;
j < traitTypes[i][thisTraitIndex].pixelCount;
j++
) {
string memory thisPixel = PandaLibrary.substring(
traitTypes[i][thisTraitIndex].pixels,
j * 4,
j * 4 + 4
);
uint8 x = letterToNumber(
PandaLibrary.substring(thisPixel, 0, 1)
);
uint8 y = letterToNumber(
PandaLibrary.substring(thisPixel, 1, 2)
);
if (placedPixels[x][y]) continue;
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
PandaLibrary.substring(thisPixel, 2, 4),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
placedPixels[x][y] = true;
}
}
}
//* @dev: Additions to Anonymice to handle animation SVG strings
if (use_pp) bg=11;
svgString = string(
abi.encodePacked(
'<svg id="panda-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <g id="panda">',
bg==5 ? specials [10] : '',
svgString,
use_toad ? specials[12] : '',
'<style> #panda { transform-origin: center;}</style><style>rect{width:1px;height:1px;} #panda-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#FFFFFF}.c02{fill:#CC0595}.c03{fill:#00FFF1}.c04{fill:#794B11}.c05{fill:#452905}.c06{fill:#477764}.c07{fill:#F2E93B}.c08{fill:#373737}.c09{fill:#E9D5AB}.c10{fill:#BA7454}.c11{fill:#FF5009}.c12{fill:#FF0846}.c13{fill:#FE08B8}.c14{fill:#C008FF}.c15{fill:#720EFF}.c16{fill:#575757}.c17{fill:#0F37FF}.c18{fill:#0F87FF}.c19{fill:#0FD2FC}.c20{fill:#12FF8F}.c21{fill:#8BFF18}.c22{fill:#E7BB5A}.c23{fill:#99711B}.c24{fill:#808080}.c25{fill:#6094B3}.c26{fill:#60B3AB}.c27{fill:#60B37B}.c28{fill:#81B360}.c29{fill:#AAB360}.c30{fill:#B39260}.c31{fill:#B36C60}.c32{fill:#AEAEAE}.c33{fill:#6082B3}.c34{fill:#6068B3}.c35{fill:#7560B3}.c36{fill:#8860B3}.c37{fill:#A760B3}.c38{fill:#B3609E}.c39{fill:#B36075}.c40{fill:#DADADA}.c41{fill:#3B2B20}.c42{fill:#D12A2F}.c43{fill:#EBE4D8}.c44{fill:#2AA792}.c45{fill:#121A33}.c46{fill:#B8D9CE}.c47{fill:#7D6E80}.c48{fill:#9D7400}.c49{fill:#80B2FF}.c50{fill:#E25B26}.c51{fill:#6CD8F0}.c52{fill:#1A9CE7}.c53{fill:#3701F0}.c54{fill:#7115E6}.c55{fill:#C104FA}.c56{fill:#62001A}.c57{fill:#92E52A}.c58{fill:#FBEE25}.c59{fill:#FD9E0F}.c60{fill:#F40917}.c61{fill:#FE069E} </style>',
specials[bg],
'</g></svg>'
)
);
return svgString;
}
/**
* @dev Hash to metadata function
*/
function hashToMetadata(string memory _hash)
public
view
returns (string memory)
{
string memory metadataString;
for (uint8 i = 0; i < 9; i++) {
uint8 thisTraitIndex = PandaLibrary.parseInt(
PandaLibrary.substring(_hash, i, i + 1)
);
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
traitTypes[i][thisTraitIndex].traitType,
'","value":"',
traitTypes[i][thisTraitIndex].traitName,
'"}'
)
);
if (i != 8)
metadataString = string(abi.encodePacked(metadataString, ","));
}
return string(abi.encodePacked("[", metadataString, "]"));
}
/**
* @dev Returns the SVG and metadata for a token Id
* @param _tokenId The tokenId to return the SVG and metadata for.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId));
string memory tokenHash = _tokenIdToHash(_tokenId);
return
string(
abi.encodePacked(
"data:application/json;base64,",
PandaLibrary.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Bamboozler #',
PandaLibrary.toString(_tokenId),
'", "description": "Bamboozlers is a collection of 10,000 original pandas generated 100% on-chain. No IPFS, no API. Now go Bamboozle!", "image": "data:image/svg+xml;base64,',
PandaLibrary.encode(
bytes(hashToSVG(tokenHash))
),
'","attributes":',
hashToMetadata(tokenHash),
"}"
)
)
)
)
)
);
}
/**
* @dev Returns a hash for a given tokenId
* @param _tokenId The tokenId to return the hash for.
*/
function _tokenIdToHash(uint256 _tokenId)
public
view
returns (string memory)
{
string memory tokenHash = tokenIdToHash[_tokenId];
//If this is a burned token, override the previous hash
if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) {
tokenHash = string(
abi.encodePacked(
"1",
PandaLibrary.substring(tokenHash, 1, 9)
)
);
}
return tokenHash;
}
/**
* @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs.
* @param _wallet The wallet to get the tokens of.
*/
function walletOfOwner(address _wallet)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_wallet);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_wallet, i);
}
return tokensId;
}
/*
___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____
/ \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/
| || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_
| O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ |
| | \ / | | || || . \ | | | || | \ | | | | || || | |\ |
\___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Clears the traits.
*/
function clearTraits() public onlyOwner {
for (uint256 i = 0; i < 9; i++) {
delete traitTypes[i];
}
}
/**
* @dev Add a trait type
* @param _traitTypeIndex The trait type index
* @param traits Array of traits to add
*/
function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits)
public
onlyOwner
{
for (uint256 i = 0; i < traits.length; i++) {
traitTypes[_traitTypeIndex].push(
Trait(
traits[i].traitName,
traits[i].traitType,
traits[i].pixels,
traits[i].pixelCount
)
);
}
return;
}
/**
* @dev Sets the Shoots ERC20 address
* @param _ShootsAddress The Shoots address
*/
function setShootsAddress(address _ShootsAddress) public onlyOwner {
ShootsAddress = _ShootsAddress;
}
/**
* @dev Transfers ownership
* @param _newOwner The new owner
*/
function transferOwnership(address _newOwner) public onlyOwner {
_owner = _newOwner;
}
/**
* @dev Modifier to only allow owner to call functions
*/
modifier onlyOwner() {
require(_owner == msg.sender);
_;
}
}
// 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();
}
}
// contracts/IShoots.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
interface IShoots is IERC20 {
function burnFrom(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library PandaLibrary {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
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 parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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 {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | * @dev Burns and mints new. @param _tokenId The token to burn./Burn token | function burnForMint(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender);
_transfer(
msg.sender,
0x000000000000000000000000000000000000dEaD,
_tokenId
);
mintInternal(msg.sender);
}
| \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/
| D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_
| / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ |
| . \| || | || | | | | || | \ | | | | || || | |\ |
|__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
| 53,627 | [
1,
38,
321,
87,
471,
312,
28142,
394,
18,
225,
389,
2316,
548,
1021,
1147,
358,
18305,
18,
19,
38,
321,
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
] | [
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,
18305,
1290,
49,
474,
12,
11890,
5034,
389,
2316,
548,
13,
1071,
288,
203,
3639,
2583,
12,
8443,
951,
24899,
2316,
548,
13,
422,
1234,
18,
15330,
1769,
203,
203,
3639,
389,
13866,
12,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
16,
203,
5411,
389,
2316,
548,
203,
3639,
11272,
203,
203,
3639,
312,
474,
3061,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
96,
565,
521,
282,
342,
225,
389,
65,
342,
565,
747,
282,
521,
1377,
571,
377,
747,
225,
571,
225,
747,
565,
521,
282,
342,
225,
308,
1377,
747,
565,
571,
19,
282,
521,
571,
565,
521,
342,
19608,
19,
203,
96,
225,
463,
225,
262,
342,
225,
306,
67,
571,
225,
320,
225,
747,
565,
521,
377,
571,
282,
1001,
20081,
225,
571,
225,
747,
225,
389,
225,
571,
342,
225,
342,
96,
1377,
571,
571,
225,
747,
377,
747,
225,
389,
225,
261,
282,
521,
67,
225,
203,
96,
565,
342,
571,
565,
389,
12369,
377,
747,
225,
463,
225,
571,
565,
571,
225,
571,
67,
225,
571,
225,
571,
225,
747,
225,
571,
225,
571,
19,
225,
342,
571,
67,
96,
225,
571,
67,
96,
571,
225,
747,
225,
531,
225,
747,
225,
571,
225,
571,
64,
972,
225,
571,
203,
96,
565,
521,
571,
282,
306,
67,
571,
225,
389,
225,
747,
377,
571,
565,
571,
282,
389,
65,
571,
225,
294,
225,
747,
225,
571,
225,
342,
282,
521,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
/* work in progress -- USE AT OWN RISK.
** simple boolean Advance Requirement confirmation / condition precedent to deal closing
** owner inputs Advance Requirement details and assigns favored party addresses
** favored party confirms when Advance Requirement is satisfied */
contract Requirement is Ownable {
bool private requirementSatisfied = false;
mapping(address => bool) favored;
address[] whitelist;
string condition;
event whitelistAdded(address indexed _addr);
event Confirmed();
//allow owner to assign favored status to address, address added to whitelist of favored party addresses
function permitFavored(address _addr) public onlyOwner {
require(!favored[_addr], "Already favored");
favored[_addr] = true;
whitelist.push(_addr);
emit whitelistAdded(_addr);
}
//check if address is a favored party
function favoredParty(address _addr) public view returns(bool) {
return favored[_addr];
}
//owner may revoke favored status
function revokeFavored(address _addr) public onlyOwner {
favored[_addr] = false;
}
//view whitelisted favored party addresses (NOTE: if favored status revoked, address will remain in whitelist)
//will use for loop to iterate through whitelist array, find where address is indexed, and delete
function viewWhitelist() public view returns(address[] memory) {
return whitelist;
}
/*** optional modifier so only the favored party may call other functions
modifier onlyFavored() {
require(favored[msg.sender] == true, "Only the favored party can call this.");
_;
} ***/
//owner sets out Advance Requirement condition details or reference to provision in underlying documentation
function enterCondition(string calldata _condition) external onlyOwner {
require(!requirementSatisfied, "Advance Requirement already satisfied, details may not be changed");
condition = _condition;
}
//check details of Advance Requirement / condition precedent
function conditionContext() external view returns(string memory) {
return condition;
}
//check if the requirement/condition is satisfied (bool)
function isRequirementSatisfied() public view returns(bool) {
return requirementSatisfied;
}
//check if the requirement/condition is satisfied (string)
function isRequirementSatisfiedReply() public view returns(string memory) {
if(requirementSatisfied == true) {
return "Advance Requirement is satisfied";
} else {
return "Advance Requirement remains outstanding";
}
}
//favored party submits confirmation that the requirement/condition is satisfied
function confirmSubmit() public {
require(favored[msg.sender] == true, "Only the favored party may confirm Advance Requirement is satisfied");
require(requirementSatisfied == false, "Advance Requirement already satisfied");
requirementSatisfied = true;
emit Confirmed();
}
}
| check if the requirement/condition is satisfied (bool) | function isRequirementSatisfied() public view returns(bool) {
return requirementSatisfied;
}
| 13,019,755 | [
1,
1893,
309,
326,
12405,
19,
4175,
353,
18958,
261,
6430,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
18599,
15163,
21501,
1435,
1071,
1476,
1135,
12,
6430,
13,
288,
203,
3639,
327,
12405,
15163,
21501,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x6e55e0e3ae67C6f2056dE2DB8e2B0032f55e2542/sources/Booster.sol | @title Events emitted by a pool @notice Contains all events emitted by the pool | interface IUniswapV3PoolEvents {
event Initialize(uint160 sqrtPriceX96, int24 tick);
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
| 2,592,954 | [
1,
3783,
17826,
635,
279,
2845,
225,
8398,
777,
2641,
17826,
635,
326,
2845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
984,
291,
91,
438,
58,
23,
2864,
3783,
288,
203,
565,
871,
9190,
12,
11890,
16874,
5700,
5147,
60,
10525,
16,
509,
3247,
4024,
1769,
203,
203,
565,
871,
490,
474,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
509,
3247,
8808,
4024,
4070,
16,
203,
3639,
509,
3247,
8808,
4024,
5988,
16,
203,
3639,
2254,
10392,
3844,
16,
203,
3639,
2254,
5034,
3844,
20,
16,
203,
3639,
2254,
5034,
3844,
21,
203,
565,
11272,
203,
203,
565,
871,
9302,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
509,
3247,
8808,
4024,
4070,
16,
203,
3639,
509,
3247,
8808,
4024,
5988,
16,
203,
3639,
2254,
10392,
3844,
20,
16,
203,
3639,
2254,
10392,
3844,
21,
203,
565,
11272,
203,
203,
565,
871,
605,
321,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
509,
3247,
8808,
4024,
4070,
16,
203,
3639,
509,
3247,
8808,
4024,
5988,
16,
203,
3639,
2254,
10392,
3844,
16,
203,
3639,
2254,
5034,
3844,
20,
16,
203,
3639,
2254,
5034,
3844,
21,
203,
565,
11272,
203,
203,
565,
871,
12738,
12,
203,
3639,
1758,
8808,
5793,
16,
203,
3639,
1758,
8808,
8027,
16,
203,
3639,
509,
5034,
3844,
20,
16,
203,
3639,
509,
5034,
3844,
21,
16,
203,
3639,
2254,
16874,
5700,
5147,
60,
10525,
16,
203,
3639,
2254,
10392,
4501,
372,
24237,
16,
203,
3639,
509,
3247,
4024,
203,
565,
11272,
203,
203,
565,
871,
15014,
12,
203,
3639,
1758,
8808,
5793,
16,
203,
3639,
2
] |
pragma solidity 0.4.26; // optimization enabled, runs: 500
/************** TPL Extended Jurisdiction - YES token integration *************
* This digital jurisdiction supports assigning YES token, or other contracts *
* with a similar validation mechanism, as additional attribute validators. *
* https://github.com/TPL-protocol/tpl-contracts/tree/yes-token-integration *
* Implements an Attribute Registry https://github.com/0age/AttributeRegistry *
* *
* Source layout: Line # *
* - library ECDSA 41 *
* - library SafeMath 108 *
* - library Roles 172 *
* - contract PauserRole 212 *
* - using Roles for Roles.Role *
* - contract Pausable 257 *
* - is PauserRole *
* - contract Ownable 313 *
* - interface AttributeRegistryInterface 386 *
* - interface BasicJurisdictionInterface 440 *
* - interface ExtendedJurisdictionInterface 658 *
* - interface IERC20 (partial) 926 *
* - ExtendedJurisdiction 934 *
* - is Ownable *
* - is Pausable *
* - is AttributeRegistryInterface *
* - is BasicJurisdictionInterface *
* - is ExtendedJurisdictionInterface *
* - using ECDSA for bytes32 *
* - using SafeMath for uint256 *
* *
* https://github.com/TPL-protocol/tpl-contracts/blob/master/LICENSE.md *
******************************************************************************/
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes signature)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
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)
);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @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;
}
}
/**
* @title Attribute Registry interface. EIP-165 ID: 0x5f46473f
*/
interface AttributeRegistryInterface {
/**
* @notice Check if an attribute of the type with ID `attributeTypeID` has
* been assigned to the account at `account` and is currently valid.
* @param account address The account to check for a valid attribute.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return True if the attribute is assigned and valid, false otherwise.
* @dev This function MUST return either true or false - i.e. calling this
* function MUST NOT cause the caller to revert.
*/
function hasAttribute(
address account,
uint256 attributeTypeID
) external view returns (bool);
/**
* @notice Retrieve the value of the attribute of the type with ID
* `attributeTypeID` on the account at `account`, assuming it is valid.
* @param account address The account to check for the given attribute value.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return The attribute value if the attribute is valid, reverts otherwise.
* @dev This function MUST revert if a directly preceding or subsequent
* function call to `hasAttribute` with identical `account` and
* `attributeTypeID` parameters would return false.
*/
function getAttributeValue(
address account,
uint256 attributeTypeID
) external view returns (uint256);
/**
* @notice Count the number of attribute types defined by the registry.
* @return The number of available attribute types.
* @dev This function MUST return a positive integer value - i.e. calling
* this function MUST NOT cause the caller to revert.
*/
function countAttributeTypes() external view returns (uint256);
/**
* @notice Get the ID of the attribute type at index `index`.
* @param index uint256 The index of the attribute type in question.
* @return The ID of the attribute type.
* @dev This function MUST revert if the provided `index` value falls outside
* of the range of the value returned from a directly preceding or subsequent
* function call to `countAttributeTypes`. It MUST NOT revert if the provided
* `index` value falls inside said range.
*/
function getAttributeTypeID(uint256 index) external view returns (uint256);
}
/**
* @title Basic TPL Jurisdiction Interface.
*/
interface BasicJurisdictionInterface {
// declare events
event AttributeTypeAdded(uint256 indexed attributeTypeID, string description);
event AttributeTypeRemoved(uint256 indexed attributeTypeID);
event ValidatorAdded(address indexed validator, string description);
event ValidatorRemoved(address indexed validator);
event ValidatorApprovalAdded(
address validator,
uint256 indexed attributeTypeID
);
event ValidatorApprovalRemoved(
address validator,
uint256 indexed attributeTypeID
);
event AttributeAdded(
address validator,
address indexed attributee,
uint256 attributeTypeID,
uint256 attributeValue
);
event AttributeRemoved(
address validator,
address indexed attributee,
uint256 attributeTypeID
);
/**
* @notice Add an attribute type with ID `ID` and description `description` to
* the jurisdiction.
* @param ID uint256 The ID of the attribute type to add.
* @param description string A description of the attribute type.
* @dev Once an attribute type is added with a given ID, the description of the
* attribute type cannot be changed, even if the attribute type is removed and
* added back later.
*/
function addAttributeType(uint256 ID, string description) external;
/**
* @notice Remove the attribute type with ID `ID` from the jurisdiction.
* @param ID uint256 The ID of the attribute type to remove.
* @dev All issued attributes of the given type will become invalid upon
* removal, but will become valid again if the attribute is reinstated.
*/
function removeAttributeType(uint256 ID) external;
/**
* @notice Add account `validator` as a validator with a description
* `description` who can be approved to set attributes of specific types.
* @param validator address The account to assign as the validator.
* @param description string A description of the validator.
* @dev Note that the jurisdiction can add iteslf as a validator if desired.
*/
function addValidator(address validator, string description) external;
/**
* @notice Remove the validator at address `validator` from the jurisdiction.
* @param validator address The account of the validator to remove.
* @dev Any attributes issued by the validator will become invalid upon their
* removal. If the validator is reinstated, those attributes will become valid
* again. Any approvals to issue attributes of a given type will need to be
* set from scratch in the event a validator is reinstated.
*/
function removeValidator(address validator) external;
/**
* @notice Approve the validator at address `validator` to issue attributes of
* the type with ID `attributeTypeID`.
* @param validator address The account of the validator to approve.
* @param attributeTypeID uint256 The ID of the approved attribute type.
*/
function addValidatorApproval(
address validator,
uint256 attributeTypeID
) external;
/**
* @notice Deny the validator at address `validator` the ability to continue to
* issue attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator with removed approval.
* @param attributeTypeID uint256 The ID of the attribute type to unapprove.
* @dev Any attributes of the specified type issued by the validator in
* question will become invalid once the approval is removed. If the approval
* is reinstated, those attributes will become valid again. The approval will
* also be removed if the approved validator is removed.
*/
function removeValidatorApproval(
address validator,
uint256 attributeTypeID
) external;
/**
* @notice Issue an attribute of the type with ID `attributeTypeID` and a value
* of `value` to `account` if `message.caller.address()` is approved validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @param value uint256 An optional value for the issued attribute.
* @dev Existing attributes of the given type on the address must be removed
* in order to set a new attribute. Be aware that ownership of the account to
* which the attribute is assigned may still be transferable - restricting
* assignment to externally-owned accounts may partially alleviate this issue.
*/
function issueAttribute(
address account,
uint256 attributeTypeID,
uint256 value
) external payable;
/**
* @notice Revoke the attribute of the type with ID `attributeTypeID` from
* `account` if `message.caller.address()` is the issuing validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @dev Validators may still revoke issued attributes even after they have been
* removed or had their approval to issue the attribute type removed - this
* enables them to address any objectionable issuances before being reinstated.
*/
function revokeAttribute(
address account,
uint256 attributeTypeID
) external;
/**
* @notice Determine if a validator at account `validator` is able to issue
* attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator.
* @param attributeTypeID uint256 The ID of the attribute type to check.
* @return True if the validator can issue attributes of the given type, false
* otherwise.
*/
function canIssueAttributeType(
address validator,
uint256 attributeTypeID
) external view returns (bool);
/**
* @notice Get a description of the attribute type with ID `attributeTypeID`.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return A description of the attribute type.
*/
function getAttributeTypeDescription(
uint256 attributeTypeID
) external view returns (string description);
/**
* @notice Get a description of the validator at account `validator`.
* @param validator address The account of the validator in question.
* @return A description of the validator.
*/
function getValidatorDescription(
address validator
) external view returns (string description);
/**
* @notice Find the validator that issued the attribute of the type with ID
* `attributeTypeID` on the account at `account` and determine if the
* validator is still valid.
* @param account address The account that contains the attribute be checked.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @return The validator and the current status of the validator as it
* pertains to the attribute type in question.
* @dev if no attribute of the given attribute type exists on the account, the
* function will return (address(0), false).
*/
function getAttributeValidator(
address account,
uint256 attributeTypeID
) external view returns (address validator, bool isStillValid);
/**
* @notice Count the number of attribute types defined by the jurisdiction.
* @return The number of available attribute types.
*/
function countAttributeTypes() external view returns (uint256);
/**
* @notice Get the ID of the attribute type at index `index`.
* @param index uint256 The index of the attribute type in question.
* @return The ID of the attribute type.
*/
function getAttributeTypeID(uint256 index) external view returns (uint256);
/**
* @notice Get the IDs of all available attribute types on the jurisdiction.
* @return A dynamic array containing all available attribute type IDs.
*/
function getAttributeTypeIDs() external view returns (uint256[]);
/**
* @notice Count the number of validators defined by the jurisdiction.
* @return The number of defined validators.
*/
function countValidators() external view returns (uint256);
/**
* @notice Get the account of the validator at index `index`.
* @param index uint256 The index of the validator in question.
* @return The account of the validator.
*/
function getValidator(uint256 index) external view returns (address);
/**
* @notice Get the accounts of all available validators on the jurisdiction.
* @return A dynamic array containing all available validator accounts.
*/
function getValidators() external view returns (address[]);
}
/**
* @title Extended TPL Jurisdiction Interface.
* @dev this extends BasicJurisdictionInterface for additional functionality.
*/
interface ExtendedJurisdictionInterface {
// declare events (NOTE: consider which fields should be indexed)
event ValidatorSigningKeyModified(
address indexed validator,
address newSigningKey
);
event StakeAllocated(
address indexed staker,
uint256 indexed attribute,
uint256 amount
);
event StakeRefunded(
address indexed staker,
uint256 indexed attribute,
uint256 amount
);
event FeePaid(
address indexed recipient,
address indexed payee,
uint256 indexed attribute,
uint256 amount
);
event TransactionRebatePaid(
address indexed submitter,
address indexed payee,
uint256 indexed attribute,
uint256 amount
);
/**
* @notice Add a restricted attribute type with ID `ID` and description
* `description` to the jurisdiction. Restricted attribute types can only be
* removed by the issuing validator or the jurisdiction.
* @param ID uint256 The ID of the restricted attribute type to add.
* @param description string A description of the restricted attribute type.
* @dev Once an attribute type is added with a given ID, the description or the
* restricted status of the attribute type cannot be changed, even if the
* attribute type is removed and added back later.
*/
function addRestrictedAttributeType(uint256 ID, string description) external;
/**
* @notice Enable or disable a restriction for a given attribute type ID `ID`
* that prevents attributes of the given type from being set by operators based
* on the provided value for `onlyPersonal`.
* @param ID uint256 The attribute type ID in question.
* @param onlyPersonal bool Whether the address may only be set personally.
*/
function setAttributeTypeOnlyPersonal(uint256 ID, bool onlyPersonal) external;
/**
* @notice Set a secondary source for a given attribute type ID `ID`, with an
* address `registry` of the secondary source in question and a given
* `sourceAttributeTypeID` for attribute type ID to check on the secondary
* source. The secondary source will only be checked for the given attribute in
* cases where no attribute of the given attribute type ID is assigned locally.
* @param ID uint256 The attribute type ID to set the secondary source for.
* @param attributeRegistry address The secondary attribute registry account.
* @param sourceAttributeTypeID uint256 The attribute type ID on the secondary
* source to check.
* @dev To remove a secondary source on an attribute type, the registry address
* should be set to the null address.
*/
function setAttributeTypeSecondarySource(
uint256 ID,
address attributeRegistry,
uint256 sourceAttributeTypeID
) external;
/**
* @notice Set a minimum required stake for a given attribute type ID `ID` and
* an amount of `stake`, to be locked in the jurisdiction upon assignment of
* attributes of the given type. The stake will be applied toward a transaction
* rebate in the event the attribute is revoked, with the remainder returned to
* the staker.
* @param ID uint256 The attribute type ID to set a minimum required stake for.
* @param minimumRequiredStake uint256 The minimum required funds to lock up.
* @dev To remove a stake requirement from an attribute type, the stake amount
* should be set to 0.
*/
function setAttributeTypeMinimumRequiredStake(
uint256 ID,
uint256 minimumRequiredStake
) external;
/**
* @notice Set a required fee for a given attribute type ID `ID` and an amount
* of `fee`, to be paid to the owner of the jurisdiction upon assignment of
* attributes of the given type.
* @param ID uint256 The attribute type ID to set the required fee for.
* @param fee uint256 The required fee amount to be paid upon assignment.
* @dev To remove a fee requirement from an attribute type, the fee amount
* should be set to 0.
*/
function setAttributeTypeJurisdictionFee(uint256 ID, uint256 fee) external;
/**
* @notice Set the public address associated with a validator signing key, used
* to sign off-chain attribute approvals, as `newSigningKey`.
* @param newSigningKey address The address associated with signing key to set.
*/
function setValidatorSigningKey(address newSigningKey) external;
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account of `msg.sender` by passing in a signed attribute approval with
* signature `signature`.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
*/
function addAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable;
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
*/
function removeAttribute(uint256 attributeTypeID) external;
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account `account` by passing in a signed attribute approval with signature
* `signature`.
* @param account address The account to add the attribute to.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function addAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable;
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `account`.
* @param account address The account to remove the attribute from.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function removeAttributeFor(address account, uint256 attributeTypeID) external;
/**
* @notice Invalidate a signed attribute approval before it has been set by
* supplying the hash of the approval `hash` and the signature `signature`.
* @param hash bytes32 The hash of the attribute approval.
* @param signature bytes The hash's signature, resolving to the signing key.
* @dev Attribute approvals can only be removed by issuing validators or the
* jurisdiction itself.
*/
function invalidateAttributeApproval(
bytes32 hash,
bytes signature
) external;
/**
* @notice Get the hash of a given attribute approval.
* @param account address The account specified by the attribute approval.
* @param operator address An optional account permitted to submit approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @return The hash of the attribute approval.
*/
function getAttributeApprovalHash(
address account,
address operator,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee
) external view returns (bytes32 hash);
/**
* @notice Check if a given signed attribute approval is currently valid when
* submitted directly by `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool);
/**
* @notice Check if a given signed attribute approval is currently valid for a
* given account when submitted by the operator at `msg.sender`.
* @param account address The account specified by the attribute approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool);
/**
* @notice Get comprehensive information on an attribute type with ID
* `attributeTypeID`.
* @param attributeTypeID uint256 The attribute type ID in question.
* @return Information on the attribute type in question.
*/
function getAttributeTypeInformation(
uint256 attributeTypeID
) external view returns (
string description,
bool isRestricted,
bool isOnlyPersonal,
address secondarySource,
uint256 secondaryId,
uint256 minimumRequiredStake,
uint256 jurisdictionFee
);
/**
* @notice Get a validator's signing key.
* @param validator address The account of the validator.
* @return The account referencing the public component of the signing key.
*/
function getValidatorSigningKey(
address validator
) external view returns (
address signingKey
);
}
/**
* @title Interface for checking attribute assignment on YES token and for token
* recovery.
*/
interface IERC20 {
function balanceOf(address) external view returns (uint256);
function transfer(address, uint256) external returns (bool);
}
/**
* @title An extended TPL jurisdiction for assigning attributes to addresses.
*/
contract ExtendedJurisdiction is Ownable, Pausable, AttributeRegistryInterface, BasicJurisdictionInterface, ExtendedJurisdictionInterface {
using ECDSA for bytes32;
using SafeMath for uint256;
// validators are entities who can add or authorize addition of new attributes
struct Validator {
bool exists;
uint256 index; // NOTE: consider use of uint88 to pack struct
address signingKey;
string description;
}
// attributes are properties that validators associate with specific addresses
struct IssuedAttribute {
bool exists;
bool setPersonally;
address operator;
address validator;
uint256 value;
uint256 stake;
}
// attributes also have associated type - metadata common to each attribute
struct AttributeType {
bool exists;
bool restricted;
bool onlyPersonal;
uint256 index; // NOTE: consider use of uint72 to pack struct
address secondarySource;
uint256 secondaryAttributeTypeID;
uint256 minimumStake;
uint256 jurisdictionFee;
string description;
mapping(address => bool) approvedValidators;
}
// top-level information about attribute types is held in a mapping of structs
mapping(uint256 => AttributeType) private _attributeTypes;
// the jurisdiction retains a mapping of addresses with assigned attributes
mapping(address => mapping(uint256 => IssuedAttribute)) private _issuedAttributes;
// there is also a mapping to identify all approved validators and their keys
mapping(address => Validator) private _validators;
// each registered signing key maps back to a specific validator
mapping(address => address) private _signingKeys;
// once attribute types are assigned to an ID, they cannot be modified
mapping(uint256 => bytes32) private _attributeTypeHashes;
// submitted attribute approvals are retained to prevent reuse after removal
mapping(bytes32 => bool) private _invalidAttributeApprovalHashes;
// attribute approvals by validator are held in a mapping
mapping(address => uint256[]) private _validatorApprovals;
// attribute approval index by validator is tracked as well
mapping(address => mapping(uint256 => uint256)) private _validatorApprovalsIndex;
// IDs for all supplied attributes are held in an array (enables enumeration)
uint256[] private _attributeIDs;
// addresses for all designated validators are also held in an array
address[] private _validatorAccounts;
// track any recoverable funds locked in the contract
uint256 private _recoverableFunds;
/**
* @notice Add an attribute type with ID `ID` and description `description` to
* the jurisdiction.
* @param ID uint256 The ID of the attribute type to add.
* @param description string A description of the attribute type.
* @dev Once an attribute type is added with a given ID, the description of the
* attribute type cannot be changed, even if the attribute type is removed and
* added back later.
*/
function addAttributeType(
uint256 ID,
string description
) external onlyOwner whenNotPaused {
// prevent existing attributes with the same id from being overwritten
require(
!isAttributeType(ID),
"an attribute type with the provided ID already exists"
);
// calculate a hash of the attribute type based on the type's properties
bytes32 hash = keccak256(
abi.encodePacked(
ID, false, description
)
);
// store hash if attribute type is the first one registered with provided ID
if (_attributeTypeHashes[ID] == bytes32(0)) {
_attributeTypeHashes[ID] = hash;
}
// prevent addition if different attribute type with the same ID has existed
require(
hash == _attributeTypeHashes[ID],
"attribute type properties must match initial properties assigned to ID"
);
// set the attribute mapping, assigning the index as the end of attributeID
_attributeTypes[ID] = AttributeType({
exists: true,
restricted: false, // when true: users can't remove attribute
onlyPersonal: false, // when true: operators can't add attribute
index: _attributeIDs.length,
secondarySource: address(0), // the address of a remote registry
secondaryAttributeTypeID: uint256(0), // the attribute type id to query
minimumStake: uint256(0), // when > 0: users must stake ether to set
jurisdictionFee: uint256(0),
description: description
// NOTE: no approvedValidators variable declaration - must be added later
});
// add the attribute type id to the end of the attributeID array
_attributeIDs.push(ID);
// log the addition of the attribute type
emit AttributeTypeAdded(ID, description);
}
/**
* @notice Add a restricted attribute type with ID `ID` and description
* `description` to the jurisdiction. Restricted attribute types can only be
* removed by the issuing validator or the jurisdiction.
* @param ID uint256 The ID of the restricted attribute type to add.
* @param description string A description of the restricted attribute type.
* @dev Once an attribute type is added with a given ID, the description or the
* restricted status of the attribute type cannot be changed, even if the
* attribute type is removed and added back later.
*/
function addRestrictedAttributeType(
uint256 ID,
string description
) external onlyOwner whenNotPaused {
// prevent existing attributes with the same id from being overwritten
require(
!isAttributeType(ID),
"an attribute type with the provided ID already exists"
);
// calculate a hash of the attribute type based on the type's properties
bytes32 hash = keccak256(
abi.encodePacked(
ID, true, description
)
);
// store hash if attribute type is the first one registered with provided ID
if (_attributeTypeHashes[ID] == bytes32(0)) {
_attributeTypeHashes[ID] = hash;
}
// prevent addition if different attribute type with the same ID has existed
require(
hash == _attributeTypeHashes[ID],
"attribute type properties must match initial properties assigned to ID"
);
// set the attribute mapping, assigning the index as the end of attributeID
_attributeTypes[ID] = AttributeType({
exists: true,
restricted: true, // when true: users can't remove attribute
onlyPersonal: false, // when true: operators can't add attribute
index: _attributeIDs.length,
secondarySource: address(0), // the address of a remote registry
secondaryAttributeTypeID: uint256(0), // the attribute type id to query
minimumStake: uint256(0), // when > 0: users must stake ether to set
jurisdictionFee: uint256(0),
description: description
// NOTE: no approvedValidators variable declaration - must be added later
});
// add the attribute type id to the end of the attributeID array
_attributeIDs.push(ID);
// log the addition of the attribute type
emit AttributeTypeAdded(ID, description);
}
/**
* @notice Enable or disable a restriction for a given attribute type ID `ID`
* that prevents attributes of the given type from being set by operators based
* on the provided value for `onlyPersonal`.
* @param ID uint256 The attribute type ID in question.
* @param onlyPersonal bool Whether the address may only be set personally.
*/
function setAttributeTypeOnlyPersonal(uint256 ID, bool onlyPersonal) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set to only personal, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].onlyPersonal = onlyPersonal;
}
/**
* @notice Set a secondary source for a given attribute type ID `ID`, with an
* address `registry` of the secondary source in question and a given
* `sourceAttributeTypeID` for attribute type ID to check on the secondary
* source. The secondary source will only be checked for the given attribute in
* cases where no attribute of the given attribute type ID is assigned locally.
* @param ID uint256 The attribute type ID to set the secondary source for.
* @param attributeRegistry address The secondary attribute registry account.
* @param sourceAttributeTypeID uint256 The attribute type ID on the secondary
* source to check.
* @dev To remove a secondary source on an attribute type, the registry address
* should be set to the null address.
*/
function setAttributeTypeSecondarySource(
uint256 ID,
address attributeRegistry,
uint256 sourceAttributeTypeID
) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set secondary source, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].secondarySource = attributeRegistry;
_attributeTypes[ID].secondaryAttributeTypeID = sourceAttributeTypeID;
}
/**
* @notice Set a minimum required stake for a given attribute type ID `ID` and
* an amount of `stake`, to be locked in the jurisdiction upon assignment of
* attributes of the given type. The stake will be applied toward a transaction
* rebate in the event the attribute is revoked, with the remainder returned to
* the staker.
* @param ID uint256 The attribute type ID to set a minimum required stake for.
* @param minimumRequiredStake uint256 The minimum required funds to lock up.
* @dev To remove a stake requirement from an attribute type, the stake amount
* should be set to 0.
*/
function setAttributeTypeMinimumRequiredStake(
uint256 ID,
uint256 minimumRequiredStake
) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set minimum stake, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].minimumStake = minimumRequiredStake;
}
/**
* @notice Set a required fee for a given attribute type ID `ID` and an amount
* of `fee`, to be paid to the owner of the jurisdiction upon assignment of
* attributes of the given type.
* @param ID uint256 The attribute type ID to set the required fee for.
* @param fee uint256 The required fee amount to be paid upon assignment.
* @dev To remove a fee requirement from an attribute type, the fee amount
* should be set to 0.
*/
function setAttributeTypeJurisdictionFee(uint256 ID, uint256 fee) external {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to set fee, no attribute type with the provided ID"
);
// modify the attribute type in the mapping
_attributeTypes[ID].jurisdictionFee = fee;
}
/**
* @notice Remove the attribute type with ID `ID` from the jurisdiction.
* @param ID uint256 The ID of the attribute type to remove.
* @dev All issued attributes of the given type will become invalid upon
* removal, but will become valid again if the attribute is reinstated.
*/
function removeAttributeType(uint256 ID) external onlyOwner whenNotPaused {
// if the attribute type ID does not exist, there is nothing to remove
require(
isAttributeType(ID),
"unable to remove, no attribute type with the provided ID"
);
// get the attribute ID at the last index of the array
uint256 lastAttributeID = _attributeIDs[_attributeIDs.length.sub(1)];
// set the attributeID at attribute-to-delete.index to the last attribute ID
_attributeIDs[_attributeTypes[ID].index] = lastAttributeID;
// update the index of the attribute type that was moved
_attributeTypes[lastAttributeID].index = _attributeTypes[ID].index;
// remove the (now duplicate) attribute ID at the end by trimming the array
_attributeIDs.length--;
// delete the attribute type's record from the mapping
delete _attributeTypes[ID];
// log the removal of the attribute type
emit AttributeTypeRemoved(ID);
}
/**
* @notice Add account `validator` as a validator with a description
* `description` who can be approved to set attributes of specific types.
* @param validator address The account to assign as the validator.
* @param description string A description of the validator.
* @dev Note that the jurisdiction can add iteslf as a validator if desired.
*/
function addValidator(
address validator,
string description
) external onlyOwner whenNotPaused {
// check that an empty address was not provided by mistake
require(validator != address(0), "must supply a valid address");
// prevent existing validators from being overwritten
require(
!isValidator(validator),
"a validator with the provided address already exists"
);
// prevent duplicate signing keys from being created
require(
_signingKeys[validator] == address(0),
"a signing key matching the provided address already exists"
);
// create a record for the validator
_validators[validator] = Validator({
exists: true,
index: _validatorAccounts.length,
signingKey: validator, // NOTE: this will be initially set to same address
description: description
});
// set the initial signing key (the validator's address) resolving to itself
_signingKeys[validator] = validator;
// add the validator to the end of the _validatorAccounts array
_validatorAccounts.push(validator);
// log the addition of the new validator
emit ValidatorAdded(validator, description);
}
/**
* @notice Remove the validator at address `validator` from the jurisdiction.
* @param validator address The account of the validator to remove.
* @dev Any attributes issued by the validator will become invalid upon their
* removal. If the validator is reinstated, those attributes will become valid
* again. Any approvals to issue attributes of a given type will need to be
* set from scratch in the event a validator is reinstated.
*/
function removeValidator(address validator) external onlyOwner whenNotPaused {
// check that a validator exists at the provided address
require(
isValidator(validator),
"unable to remove, no validator located at the provided address"
);
// first, start removing validator approvals until gas is exhausted
while (_validatorApprovals[validator].length > 0 && gasleft() > 25000) {
// locate the index of last attribute ID in the validator approval group
uint256 lastIndex = _validatorApprovals[validator].length.sub(1);
// locate the validator approval to be removed
uint256 targetApproval = _validatorApprovals[validator][lastIndex];
// remove the record of the approval from the associated attribute type
delete _attributeTypes[targetApproval].approvedValidators[validator];
// remove the record of the index of the approval
delete _validatorApprovalsIndex[validator][targetApproval];
// drop the last attribute ID from the validator approval group
_validatorApprovals[validator].length--;
}
// require that all approvals were successfully removed
require(
_validatorApprovals[validator].length == 0,
"Cannot remove validator - first remove any existing validator approvals"
);
// get the validator address at the last index of the array
address lastAccount = _validatorAccounts[_validatorAccounts.length.sub(1)];
// set the address at validator-to-delete.index to last validator address
_validatorAccounts[_validators[validator].index] = lastAccount;
// update the index of the attribute type that was moved
_validators[lastAccount].index = _validators[validator].index;
// remove (duplicate) validator address at the end by trimming the array
_validatorAccounts.length--;
// remove the validator's signing key from its mapping
delete _signingKeys[_validators[validator].signingKey];
// remove the validator record
delete _validators[validator];
// log the removal of the validator
emit ValidatorRemoved(validator);
}
/**
* @notice Approve the validator at address `validator` to issue attributes of
* the type with ID `attributeTypeID`.
* @param validator address The account of the validator to approve.
* @param attributeTypeID uint256 The ID of the approved attribute type.
*/
function addValidatorApproval(
address validator,
uint256 attributeTypeID
) external onlyOwner whenNotPaused {
// check that the attribute is predefined and that the validator exists
require(
isValidator(validator) && isAttributeType(attributeTypeID),
"must specify both a valid attribute and an available validator"
);
// check that the validator is not already approved
require(
!_attributeTypes[attributeTypeID].approvedValidators[validator],
"validator is already approved on the provided attribute"
);
// set the validator approval status on the attribute
_attributeTypes[attributeTypeID].approvedValidators[validator] = true;
// add the record of the index of the validator approval to be added
uint256 index = _validatorApprovals[validator].length;
_validatorApprovalsIndex[validator][attributeTypeID] = index;
// include the attribute type in the validator approval mapping
_validatorApprovals[validator].push(attributeTypeID);
// log the addition of the validator's attribute type approval
emit ValidatorApprovalAdded(validator, attributeTypeID);
}
/**
* @notice Deny the validator at address `validator` the ability to continue to
* issue attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator with removed approval.
* @param attributeTypeID uint256 The ID of the attribute type to unapprove.
* @dev Any attributes of the specified type issued by the validator in
* question will become invalid once the approval is removed. If the approval
* is reinstated, those attributes will become valid again. The approval will
* also be removed if the approved validator is removed.
*/
function removeValidatorApproval(
address validator,
uint256 attributeTypeID
) external onlyOwner whenNotPaused {
// check that the attribute is predefined and that the validator exists
require(
canValidate(validator, attributeTypeID),
"unable to remove validator approval, attribute is already unapproved"
);
// remove the validator approval status from the attribute
delete _attributeTypes[attributeTypeID].approvedValidators[validator];
// locate the index of the last validator approval
uint256 lastIndex = _validatorApprovals[validator].length.sub(1);
// locate the last attribute ID in the validator approval group
uint256 lastAttributeID = _validatorApprovals[validator][lastIndex];
// locate the index of the validator approval to be removed
uint256 index = _validatorApprovalsIndex[validator][attributeTypeID];
// replace the validator approval with the last approval in the array
_validatorApprovals[validator][index] = lastAttributeID;
// drop the last attribute ID from the validator approval group
_validatorApprovals[validator].length--;
// update the record of the index of the swapped-in approval
_validatorApprovalsIndex[validator][lastAttributeID] = index;
// remove the record of the index of the removed approval
delete _validatorApprovalsIndex[validator][attributeTypeID];
// log the removal of the validator's attribute type approval
emit ValidatorApprovalRemoved(validator, attributeTypeID);
}
/**
* @notice Set the public address associated with a validator signing key, used
* to sign off-chain attribute approvals, as `newSigningKey`.
* @param newSigningKey address The address associated with signing key to set.
* @dev Consider having the validator submit a signed proof demonstrating that
* the provided signing key is indeed a signing key in their control - this
* helps mitigate the fringe attack vector where a validator could set the
* address of another validator candidate (especially in the case of a deployed
* smart contract) as their "signing key" in order to block them from being
* added to the jurisdiction (due to the required property of signing keys
* being unique, coupled with the fact that new validators are set up with
* their address as the default initial signing key).
*/
function setValidatorSigningKey(address newSigningKey) external {
require(
isValidator(msg.sender),
"only validators may modify validator signing keys");
// prevent duplicate signing keys from being created
require(
_signingKeys[newSigningKey] == address(0),
"a signing key matching the provided address already exists"
);
// remove validator address as the resolved value for the old key
delete _signingKeys[_validators[msg.sender].signingKey];
// set the signing key to the new value
_validators[msg.sender].signingKey = newSigningKey;
// add validator address as the resolved value for the new key
_signingKeys[newSigningKey] = msg.sender;
// log the modification of the signing key
emit ValidatorSigningKeyModified(msg.sender, newSigningKey);
}
/**
* @notice Issue an attribute of the type with ID `attributeTypeID` and a value
* of `value` to `account` if `message.caller.address()` is approved validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @param value uint256 An optional value for the issued attribute.
* @dev Existing attributes of the given type on the address must be removed
* in order to set a new attribute. Be aware that ownership of the account to
* which the attribute is assigned may still be transferable - restricting
* assignment to externally-owned accounts may partially alleviate this issue.
*/
function issueAttribute(
address account,
uint256 attributeTypeID,
uint256 value
) external payable whenNotPaused {
require(
canValidate(msg.sender, attributeTypeID),
"only approved validators may assign attributes of this type"
);
require(
!_issuedAttributes[account][attributeTypeID].exists,
"duplicate attributes are not supported, remove existing attribute first"
);
// retrieve required minimum stake and jurisdiction fees on attribute type
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
uint256 stake = msg.value.sub(jurisdictionFee);
require(
stake >= minimumStake,
"attribute requires a greater value than is currently provided"
);
// store attribute value and amount of ether staked in correct scope
_issuedAttributes[account][attributeTypeID] = IssuedAttribute({
exists: true,
setPersonally: false,
operator: address(0),
validator: msg.sender,
value: value,
stake: stake
});
// log the addition of the attribute
emit AttributeAdded(msg.sender, account, attributeTypeID, value);
// log allocation of staked funds to the attribute if applicable
if (stake > 0) {
emit StakeAllocated(msg.sender, attributeTypeID, stake);
}
// pay jurisdiction fee to the owner of the jurisdiction if applicable
if (jurisdictionFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (owner().send(jurisdictionFee)) {
emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee);
} else {
_recoverableFunds = _recoverableFunds.add(jurisdictionFee);
}
}
}
/**
* @notice Revoke the attribute of the type with ID `attributeTypeID` from
* `account` if `message.caller.address()` is the issuing validator.
* @param account address The account to issue the attribute on.
* @param attributeTypeID uint256 The ID of the attribute type to issue.
* @dev Validators may still revoke issued attributes even after they have been
* removed or had their approval to issue the attribute type removed - this
* enables them to address any objectionable issuances before being reinstated.
*/
function revokeAttribute(
address account,
uint256 attributeTypeID
) external whenNotPaused {
// ensure that an attribute with the given account and attribute exists
require(
_issuedAttributes[account][attributeTypeID].exists,
"only existing attributes may be removed"
);
// determine the assigned validator on the user attribute
address validator = _issuedAttributes[account][attributeTypeID].validator;
// caller must be either the jurisdiction owner or the assigning validator
require(
msg.sender == validator || msg.sender == owner(),
"only jurisdiction or issuing validators may revoke arbitrary attributes"
);
// determine if attribute has any stake in order to refund transaction fee
uint256 stake = _issuedAttributes[account][attributeTypeID].stake;
// determine the correct address to refund the staked amount to
address refundAddress;
if (_issuedAttributes[account][attributeTypeID].setPersonally) {
refundAddress = account;
} else {
address operator = _issuedAttributes[account][attributeTypeID].operator;
if (operator == address(0)) {
refundAddress = validator;
} else {
refundAddress = operator;
}
}
// remove the attribute from the designated user account
delete _issuedAttributes[account][attributeTypeID];
// log the removal of the attribute
emit AttributeRemoved(validator, account, attributeTypeID);
// pay out any refunds and return the excess stake to the user
if (stake > 0 && address(this).balance >= stake) {
// NOTE: send is chosen over transfer to prevent cases where a malicious
// fallback function could forcibly block an attribute's removal. Another
// option is to allow a user to pull the staked amount after the removal.
// NOTE: refine transaction rebate gas calculation! Setting this value too
// high gives validators the incentive to revoke valid attributes. Simply
// checking against gasLeft() & adding the final gas usage won't give the
// correct transaction cost, as freeing space refunds gas upon completion.
uint256 transactionGas = 37700; // <--- WARNING: THIS IS APPROXIMATE
uint256 transactionCost = transactionGas.mul(tx.gasprice);
// if stake exceeds allocated transaction cost, refund user the difference
if (stake > transactionCost) {
// refund the excess stake to the address that contributed the funds
if (refundAddress.send(stake.sub(transactionCost))) {
emit StakeRefunded(
refundAddress,
attributeTypeID,
stake.sub(transactionCost)
);
} else {
_recoverableFunds = _recoverableFunds.add(stake.sub(transactionCost));
}
// emit an event for the payment of the transaction rebate
emit TransactionRebatePaid(
tx.origin,
refundAddress,
attributeTypeID,
transactionCost
);
// refund the cost of the transaction to the trasaction submitter
tx.origin.transfer(transactionCost);
// otherwise, allocate entire stake to partially refunding the transaction
} else {
// emit an event for the payment of the partial transaction rebate
emit TransactionRebatePaid(
tx.origin,
refundAddress,
attributeTypeID,
stake
);
// refund the partial cost of the transaction to trasaction submitter
tx.origin.transfer(stake);
}
}
}
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account of `msg.sender` by passing in a signed attribute approval with
* signature `signature`.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
*/
function addAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable {
// NOTE: determine best course of action when the attribute already exists
// NOTE: consider utilizing bytes32 type for attributes and values
// NOTE: does not currently support an extraData parameter, consider adding
// NOTE: if msg.sender is a proxy contract, its ownership may be transferred
// at will, circumventing any token transfer restrictions. Restricting usage
// to only externally owned accounts may partially alleviate this concern.
// NOTE: cosider including a salt (or better, nonce) parameter so that when
// a user adds an attribute, then it gets revoked, the user can get a new
// signature from the validator and renew the attribute using that. The main
// downside is that everyone will have to keep track of the extra parameter.
// Another solution is to just modifiy the required stake or fee amount.
require(
!_issuedAttributes[msg.sender][attributeTypeID].exists,
"duplicate attributes are not supported, remove existing attribute first"
);
// retrieve required minimum stake and jurisdiction fees on attribute type
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
uint256 stake = msg.value.sub(validatorFee).sub(jurisdictionFee);
require(
stake >= minimumStake,
"attribute requires a greater value than is currently provided"
);
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
msg.sender,
address(0),
msg.value,
validatorFee,
attributeTypeID,
value
)
);
require(
!_invalidAttributeApprovalHashes[hash],
"signed attribute approvals from validators may not be reused"
);
// extract the key used to sign the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve the validator who controls the extracted key
address validator = _signingKeys[signingKey];
require(
canValidate(validator, attributeTypeID),
"signature does not match an approved validator for given attribute type"
);
// store attribute value and amount of ether staked in correct scope
_issuedAttributes[msg.sender][attributeTypeID] = IssuedAttribute({
exists: true,
setPersonally: true,
operator: address(0),
validator: validator,
value: value,
stake: stake
// NOTE: no extraData included
});
// flag the signed approval as invalid once it's been used to set attribute
_invalidAttributeApprovalHashes[hash] = true;
// log the addition of the attribute
emit AttributeAdded(validator, msg.sender, attributeTypeID, value);
// log allocation of staked funds to the attribute if applicable
if (stake > 0) {
emit StakeAllocated(msg.sender, attributeTypeID, stake);
}
// pay jurisdiction fee to the owner of the jurisdiction if applicable
if (jurisdictionFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (owner().send(jurisdictionFee)) {
emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee);
} else {
_recoverableFunds = _recoverableFunds.add(jurisdictionFee);
}
}
// pay validator fee to the issuing validator's address if applicable
if (validatorFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (validator.send(validatorFee)) {
emit FeePaid(validator, msg.sender, attributeTypeID, validatorFee);
} else {
_recoverableFunds = _recoverableFunds.add(validatorFee);
}
}
}
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
*/
function removeAttribute(uint256 attributeTypeID) external {
// attributes may only be removed by the user if they are not restricted
require(
!_attributeTypes[attributeTypeID].restricted,
"only jurisdiction or issuing validator may remove a restricted attribute"
);
require(
_issuedAttributes[msg.sender][attributeTypeID].exists,
"only existing attributes may be removed"
);
// determine the assigned validator on the user attribute
address validator = _issuedAttributes[msg.sender][attributeTypeID].validator;
// determine if the attribute has a staked value
uint256 stake = _issuedAttributes[msg.sender][attributeTypeID].stake;
// determine the correct address to refund the staked amount to
address refundAddress;
if (_issuedAttributes[msg.sender][attributeTypeID].setPersonally) {
refundAddress = msg.sender;
} else {
address operator = _issuedAttributes[msg.sender][attributeTypeID].operator;
if (operator == address(0)) {
refundAddress = validator;
} else {
refundAddress = operator;
}
}
// remove the attribute from the user address
delete _issuedAttributes[msg.sender][attributeTypeID];
// log the removal of the attribute
emit AttributeRemoved(validator, msg.sender, attributeTypeID);
// if the attribute has any staked balance, refund it to the user
if (stake > 0 && address(this).balance >= stake) {
// NOTE: send is chosen over transfer to prevent cases where a malicious
// fallback function could forcibly block an attribute's removal
if (refundAddress.send(stake)) {
emit StakeRefunded(refundAddress, attributeTypeID, stake);
} else {
_recoverableFunds = _recoverableFunds.add(stake);
}
}
}
/**
* @notice Add an attribute of the type with ID `attributeTypeID`, an attribute
* value of `value`, and an associated validator fee of `validatorFee` to
* account `account` by passing in a signed attribute approval with signature
* `signature`.
* @param account address The account to add the attribute to.
* @param attributeTypeID uint256 The ID of the attribute type to add.
* @param value uint256 The value for the attribute to add.
* @param validatorFee uint256 The fee to be paid to the issuing validator.
* @param signature bytes The signature from the validator attribute approval.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function addAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 validatorFee,
bytes signature
) external payable {
// NOTE: determine best course of action when the attribute already exists
// NOTE: consider utilizing bytes32 type for attributes and values
// NOTE: does not currently support an extraData parameter, consider adding
// NOTE: if msg.sender is a proxy contract, its ownership may be transferred
// at will, circumventing any token transfer restrictions. Restricting usage
// to only externally owned accounts may partially alleviate this concern.
// NOTE: consider including a salt (or better, nonce) parameter so that when
// a user adds an attribute, then it gets revoked, the user can get a new
// signature from the validator and renew the attribute using that. The main
// downside is that everyone will have to keep track of the extra parameter.
// Another solution is to just modifiy the required stake or fee amount.
// attributes may only be added by a third party if onlyPersonal is false
require(
!_attributeTypes[attributeTypeID].onlyPersonal,
"only operatable attributes may be added on behalf of another address"
);
require(
!_issuedAttributes[account][attributeTypeID].exists,
"duplicate attributes are not supported, remove existing attribute first"
);
// retrieve required minimum stake and jurisdiction fees on attribute type
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
uint256 stake = msg.value.sub(validatorFee).sub(jurisdictionFee);
require(
stake >= minimumStake,
"attribute requires a greater value than is currently provided"
);
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = keccak256(
abi.encodePacked(
address(this),
account,
msg.sender,
msg.value,
validatorFee,
attributeTypeID,
value
)
);
require(
!_invalidAttributeApprovalHashes[hash],
"signed attribute approvals from validators may not be reused"
);
// extract the key used to sign the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve the validator who controls the extracted key
address validator = _signingKeys[signingKey];
require(
canValidate(validator, attributeTypeID),
"signature does not match an approved validator for provided attribute"
);
// store attribute value and amount of ether staked in correct scope
_issuedAttributes[account][attributeTypeID] = IssuedAttribute({
exists: true,
setPersonally: false,
operator: msg.sender,
validator: validator,
value: value,
stake: stake
// NOTE: no extraData included
});
// flag the signed approval as invalid once it's been used to set attribute
_invalidAttributeApprovalHashes[hash] = true;
// log the addition of the attribute
emit AttributeAdded(validator, account, attributeTypeID, value);
// log allocation of staked funds to the attribute if applicable
// NOTE: the staker is the entity that pays the fee here!
if (stake > 0) {
emit StakeAllocated(msg.sender, attributeTypeID, stake);
}
// pay jurisdiction fee to the owner of the jurisdiction if applicable
if (jurisdictionFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (owner().send(jurisdictionFee)) {
emit FeePaid(owner(), msg.sender, attributeTypeID, jurisdictionFee);
} else {
_recoverableFunds = _recoverableFunds.add(jurisdictionFee);
}
}
// pay validator fee to the issuing validator's address if applicable
if (validatorFee > 0) {
// NOTE: send is chosen over transfer to prevent cases where a improperly
// configured fallback function could block addition of an attribute
if (validator.send(validatorFee)) {
emit FeePaid(validator, msg.sender, attributeTypeID, validatorFee);
} else {
_recoverableFunds = _recoverableFunds.add(validatorFee);
}
}
}
/**
* @notice Remove an attribute of the type with ID `attributeTypeID` from
* account of `account`.
* @param account address The account to remove the attribute from.
* @param attributeTypeID uint256 The ID of the attribute type to remove.
* @dev Restricted attribute types can only be removed by issuing validators or
* the jurisdiction itself.
*/
function removeAttributeFor(address account, uint256 attributeTypeID) external {
// attributes may only be removed by the user if they are not restricted
require(
!_attributeTypes[attributeTypeID].restricted,
"only jurisdiction or issuing validator may remove a restricted attribute"
);
require(
_issuedAttributes[account][attributeTypeID].exists,
"only existing attributes may be removed"
);
require(
_issuedAttributes[account][attributeTypeID].operator == msg.sender,
"only an assigning operator may remove attribute on behalf of an address"
);
// determine the assigned validator on the user attribute
address validator = _issuedAttributes[account][attributeTypeID].validator;
// determine if the attribute has a staked value
uint256 stake = _issuedAttributes[account][attributeTypeID].stake;
// remove the attribute from the user address
delete _issuedAttributes[account][attributeTypeID];
// log the removal of the attribute
emit AttributeRemoved(validator, account, attributeTypeID);
// if the attribute has any staked balance, refund it to the user
if (stake > 0 && address(this).balance >= stake) {
// NOTE: send is chosen over transfer to prevent cases where a malicious
// fallback function could forcibly block an attribute's removal
if (msg.sender.send(stake)) {
emit StakeRefunded(msg.sender, attributeTypeID, stake);
} else {
_recoverableFunds = _recoverableFunds.add(stake);
}
}
}
/**
* @notice Invalidate a signed attribute approval before it has been set by
* supplying the hash of the approval `hash` and the signature `signature`.
* @param hash bytes32 The hash of the attribute approval.
* @param signature bytes The hash's signature, resolving to the signing key.
* @dev Attribute approvals can only be removed by issuing validators or the
* jurisdiction itself.
*/
function invalidateAttributeApproval(
bytes32 hash,
bytes signature
) external {
// determine the assigned validator on the signed attribute approval
address validator = _signingKeys[
hash.toEthSignedMessageHash().recover(signature) // signingKey
];
// caller must be either the jurisdiction owner or the assigning validator
require(
msg.sender == validator || msg.sender == owner(),
"only jurisdiction or issuing validator may invalidate attribute approval"
);
// add the hash to the set of invalid attribute approval hashes
_invalidAttributeApprovalHashes[hash] = true;
}
/**
* @notice Check if an attribute of the type with ID `attributeTypeID` has
* been assigned to the account at `account` and is currently valid.
* @param account address The account to check for a valid attribute.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return True if the attribute is assigned and valid, false otherwise.
* @dev This function MUST return either true or false - i.e. calling this
* function MUST NOT cause the caller to revert.
*/
function hasAttribute(
address account,
uint256 attributeTypeID
) external view returns (bool) {
address validator = _issuedAttributes[account][attributeTypeID].validator;
return (
(
_validators[validator].exists && // isValidator(validator)
_attributeTypes[attributeTypeID].approvedValidators[validator] &&
_attributeTypes[attributeTypeID].exists //isAttributeType(attributeTypeID)
) || (
_attributeTypes[attributeTypeID].secondarySource != address(0) &&
secondaryHasAttribute(
_attributeTypes[attributeTypeID].secondarySource,
account,
_attributeTypes[attributeTypeID].secondaryAttributeTypeID
)
)
);
}
/**
* @notice Retrieve the value of the attribute of the type with ID
* `attributeTypeID` on the account at `account`, assuming it is valid.
* @param account address The account to check for the given attribute value.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return The attribute value if the attribute is valid, reverts otherwise.
* @dev This function MUST revert if a directly preceding or subsequent
* function call to `hasAttribute` with identical `account` and
* `attributeTypeID` parameters would return false.
*/
function getAttributeValue(
address account,
uint256 attributeTypeID
) external view returns (uint256 value) {
// gas optimization: get validator & call canValidate function body directly
address validator = _issuedAttributes[account][attributeTypeID].validator;
if (
_validators[validator].exists && // isValidator(validator)
_attributeTypes[attributeTypeID].approvedValidators[validator] &&
_attributeTypes[attributeTypeID].exists //isAttributeType(attributeTypeID)
) {
return _issuedAttributes[account][attributeTypeID].value;
} else if (
_attributeTypes[attributeTypeID].secondarySource != address(0)
) {
// if attributeTypeID = uint256 of 'wyre-yes-token', use special handling
if (_attributeTypes[attributeTypeID].secondaryAttributeTypeID == 2423228754106148037712574142965102) {
require(
IERC20(
_attributeTypes[attributeTypeID].secondarySource
).balanceOf(account) >= 1,
"no Yes Token has been issued to the provided account"
);
return 1; // this could also return a specific yes token's country code?
}
// first ensure hasAttribute on the secondary source returns true
require(
AttributeRegistryInterface(
_attributeTypes[attributeTypeID].secondarySource
).hasAttribute(
account, _attributeTypes[attributeTypeID].secondaryAttributeTypeID
),
"attribute of the provided type is not assigned to the provided account"
);
return (
AttributeRegistryInterface(
_attributeTypes[attributeTypeID].secondarySource
).getAttributeValue(
account, _attributeTypes[attributeTypeID].secondaryAttributeTypeID
)
);
}
// NOTE: checking for values of invalid attributes will revert
revert("could not find an attribute value at the provided account and ID");
}
/**
* @notice Determine if a validator at account `validator` is able to issue
* attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator.
* @param attributeTypeID uint256 The ID of the attribute type to check.
* @return True if the validator can issue attributes of the given type, false
* otherwise.
*/
function canIssueAttributeType(
address validator,
uint256 attributeTypeID
) external view returns (bool) {
return canValidate(validator, attributeTypeID);
}
/**
* @notice Get a description of the attribute type with ID `attributeTypeID`.
* @param attributeTypeID uint256 The ID of the attribute type to check for.
* @return A description of the attribute type.
*/
function getAttributeTypeDescription(
uint256 attributeTypeID
) external view returns (
string description
) {
return _attributeTypes[attributeTypeID].description;
}
/**
* @notice Get comprehensive information on an attribute type with ID
* `attributeTypeID`.
* @param attributeTypeID uint256 The attribute type ID in question.
* @return Information on the attribute type in question.
*/
function getAttributeTypeInformation(
uint256 attributeTypeID
) external view returns (
string description,
bool isRestricted,
bool isOnlyPersonal,
address secondarySource,
uint256 secondaryAttributeTypeID,
uint256 minimumRequiredStake,
uint256 jurisdictionFee
) {
return (
_attributeTypes[attributeTypeID].description,
_attributeTypes[attributeTypeID].restricted,
_attributeTypes[attributeTypeID].onlyPersonal,
_attributeTypes[attributeTypeID].secondarySource,
_attributeTypes[attributeTypeID].secondaryAttributeTypeID,
_attributeTypes[attributeTypeID].minimumStake,
_attributeTypes[attributeTypeID].jurisdictionFee
);
}
/**
* @notice Get a description of the validator at account `validator`.
* @param validator address The account of the validator in question.
* @return A description of the validator.
*/
function getValidatorDescription(
address validator
) external view returns (
string description
) {
return _validators[validator].description;
}
/**
* @notice Get the signing key of the validator at account `validator`.
* @param validator address The account of the validator in question.
* @return The signing key of the validator.
*/
function getValidatorSigningKey(
address validator
) external view returns (
address signingKey
) {
return _validators[validator].signingKey;
}
/**
* @notice Find the validator that issued the attribute of the type with ID
* `attributeTypeID` on the account at `account` and determine if the
* validator is still valid.
* @param account address The account that contains the attribute be checked.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @return The validator and the current status of the validator as it
* pertains to the attribute type in question.
* @dev if no attribute of the given attribute type exists on the account, the
* function will return (address(0), false).
*/
function getAttributeValidator(
address account,
uint256 attributeTypeID
) external view returns (
address validator,
bool isStillValid
) {
address issuer = _issuedAttributes[account][attributeTypeID].validator;
return (issuer, canValidate(issuer, attributeTypeID));
}
/**
* @notice Count the number of attribute types defined by the registry.
* @return The number of available attribute types.
* @dev This function MUST return a positive integer value - i.e. calling
* this function MUST NOT cause the caller to revert.
*/
function countAttributeTypes() external view returns (uint256) {
return _attributeIDs.length;
}
/**
* @notice Get the ID of the attribute type at index `index`.
* @param index uint256 The index of the attribute type in question.
* @return The ID of the attribute type.
* @dev This function MUST revert if the provided `index` value falls outside
* of the range of the value returned from a directly preceding or subsequent
* function call to `countAttributeTypes`. It MUST NOT revert if the provided
* `index` value falls inside said range.
*/
function getAttributeTypeID(uint256 index) external view returns (uint256) {
require(
index < _attributeIDs.length,
"provided index is outside of the range of defined attribute type IDs"
);
return _attributeIDs[index];
}
/**
* @notice Get the IDs of all available attribute types on the jurisdiction.
* @return A dynamic array containing all available attribute type IDs.
*/
function getAttributeTypeIDs() external view returns (uint256[]) {
return _attributeIDs;
}
/**
* @notice Count the number of validators defined by the jurisdiction.
* @return The number of defined validators.
*/
function countValidators() external view returns (uint256) {
return _validatorAccounts.length;
}
/**
* @notice Get the account of the validator at index `index`.
* @param index uint256 The index of the validator in question.
* @return The account of the validator.
*/
function getValidator(
uint256 index
) external view returns (address) {
return _validatorAccounts[index];
}
/**
* @notice Get the accounts of all available validators on the jurisdiction.
* @return A dynamic array containing all available validator accounts.
*/
function getValidators() external view returns (address[]) {
return _validatorAccounts;
}
/**
* @notice Determine if the interface ID `interfaceID` is supported (ERC-165)
* @param interfaceID bytes4 The interface ID in question.
* @return True if the interface is supported, false otherwise.
* @dev this function will produce a compiler warning recommending that the
* visibility be set to pure, but the interface expects a view function.
* Supported interfaces include ERC-165 (0x01ffc9a7) and the attribute
* registry interface (0x5f46473f).
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return (
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == (
this.hasAttribute.selector
^ this.getAttributeValue.selector
^ this.countAttributeTypes.selector
^ this.getAttributeTypeID.selector
) // AttributeRegistryInterface
); // 0x01ffc9a7 || 0x5f46473f
}
/**
* @notice Get the hash of a given attribute approval.
* @param account address The account specified by the attribute approval.
* @param operator address An optional account permitted to submit approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @return The hash of the attribute approval.
*/
function getAttributeApprovalHash(
address account,
address operator,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee
) external view returns (
bytes32 hash
) {
return calculateAttributeApprovalHash(
account,
operator,
attributeTypeID,
value,
fundsRequired,
validatorFee
);
}
/**
* @notice Check if a given signed attribute approval is currently valid when
* submitted directly by `msg.sender`.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttribute(
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool) {
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = calculateAttributeApprovalHash(
msg.sender,
address(0),
attributeTypeID,
value,
fundsRequired,
validatorFee
);
// recover the address associated with the signature of the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve variables necessary to perform checks
address validator = _signingKeys[signingKey];
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
// determine if the attribute can currently be added.
// NOTE: consider returning an error code along with the boolean.
return (
fundsRequired >= minimumStake.add(jurisdictionFee).add(validatorFee) &&
!_invalidAttributeApprovalHashes[hash] &&
canValidate(validator, attributeTypeID) &&
!_issuedAttributes[msg.sender][attributeTypeID].exists
);
}
/**
* @notice Check if a given signed attribute approval is currently valid for a
* given account when submitted by the operator at `msg.sender`.
* @param account address The account specified by the attribute approval.
* @param attributeTypeID uint256 The ID of the attribute type in question.
* @param value uint256 The value of the attribute in the approval.
* @param fundsRequired uint256 The amount to be included with the approval.
* @param validatorFee uint256 The required fee to be paid to the validator.
* @param signature bytes The attribute approval signature, based on a hash of
* the other parameters and the submitting account.
* @return True if the approval is currently valid, false otherwise.
*/
function canAddAttributeFor(
address account,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee,
bytes signature
) external view returns (bool) {
// signed data hash constructed according to EIP-191-0x45 to prevent replays
bytes32 hash = calculateAttributeApprovalHash(
account,
msg.sender,
attributeTypeID,
value,
fundsRequired,
validatorFee
);
// recover the address associated with the signature of the message hash
address signingKey = hash.toEthSignedMessageHash().recover(signature);
// retrieve variables necessary to perform checks
address validator = _signingKeys[signingKey];
uint256 minimumStake = _attributeTypes[attributeTypeID].minimumStake;
uint256 jurisdictionFee = _attributeTypes[attributeTypeID].jurisdictionFee;
// determine if the attribute can currently be added.
// NOTE: consider returning an error code along with the boolean.
return (
fundsRequired >= minimumStake.add(jurisdictionFee).add(validatorFee) &&
!_invalidAttributeApprovalHashes[hash] &&
canValidate(validator, attributeTypeID) &&
!_issuedAttributes[account][attributeTypeID].exists
);
}
/**
* @notice Determine if an attribute type with ID `attributeTypeID` is
* currently defined on the jurisdiction.
* @param attributeTypeID uint256 The attribute type ID in question.
* @return True if the attribute type is defined, false otherwise.
*/
function isAttributeType(uint256 attributeTypeID) public view returns (bool) {
return _attributeTypes[attributeTypeID].exists;
}
/**
* @notice Determine if the account `account` is currently assigned as a
* validator on the jurisdiction.
* @param account address The account to check for validator status.
* @return True if the account is assigned as a validator, false otherwise.
*/
function isValidator(address account) public view returns (bool) {
return _validators[account].exists;
}
/**
* @notice Check for recoverable funds that have become locked in the
* jurisdiction as a result of improperly configured receivers for payments of
* fees or remaining stake. Note that funds sent into the jurisdiction as a
* result of coinbase assignment or as the recipient of a selfdestruct will
* not be recoverable.
* @return The total tracked recoverable funds.
*/
function recoverableFunds() public view returns (uint256) {
// return the total tracked recoverable funds.
return _recoverableFunds;
}
/**
* @notice Check for recoverable tokens that are owned by the jurisdiction at
* the token contract address of `token`.
* @param token address The account where token contract is located.
* @return The total recoverable tokens.
*/
function recoverableTokens(address token) public view returns (uint256) {
// return the total tracked recoverable tokens.
return IERC20(token).balanceOf(address(this));
}
/**
* @notice Recover funds that have become locked in the jurisdiction as a
* result of improperly configured receivers for payments of fees or remaining
* stake by transferring an amount of `value` to the address at `account`.
* Note that funds sent into the jurisdiction as a result of coinbase
* assignment or as the recipient of a selfdestruct will not be recoverable.
* @param account address The account to send recovered tokens.
* @param value uint256 The amount of tokens to be sent.
*/
function recoverFunds(address account, uint256 value) public onlyOwner {
// safely deduct the value from the total tracked recoverable funds.
_recoverableFunds = _recoverableFunds.sub(value);
// transfer the value to the specified account & revert if any error occurs.
account.transfer(value);
}
/**
* @notice Recover tokens that are owned by the jurisdiction at the token
* contract address of `token`, transferring an amount of `value` to the
* address at `account`.
* @param token address The account where token contract is located.
* @param account address The account to send recovered funds.
* @param value uint256 The amount of ether to be sent.
*/
function recoverTokens(
address token,
address account,
uint256 value
) public onlyOwner {
// transfer the value to the specified account & revert if any error occurs.
require(IERC20(token).transfer(account, value));
}
/**
* @notice Internal function to determine if a validator at account
* `validator` can issue attributes of the type with ID `attributeTypeID`.
* @param validator address The account of the validator.
* @param attributeTypeID uint256 The ID of the attribute type to check.
* @return True if the validator can issue attributes of the given type, false
* otherwise.
*/
function canValidate(
address validator,
uint256 attributeTypeID
) internal view returns (bool) {
return (
_validators[validator].exists && // isValidator(validator)
_attributeTypes[attributeTypeID].approvedValidators[validator] &&
_attributeTypes[attributeTypeID].exists // isAttributeType(attributeTypeID)
);
}
// internal helper function for getting the hash of an attribute approval
function calculateAttributeApprovalHash(
address account,
address operator,
uint256 attributeTypeID,
uint256 value,
uint256 fundsRequired,
uint256 validatorFee
) internal view returns (bytes32 hash) {
return keccak256(
abi.encodePacked(
address(this),
account,
operator,
fundsRequired,
validatorFee,
attributeTypeID,
value
)
);
}
// helper function, won't revert calling hasAttribute on secondary registries
function secondaryHasAttribute(
address source,
address account,
uint256 attributeTypeID
) internal view returns (bool result) {
// if attributeTypeID = uint256 of 'wyre-yes-token', use special handling
if (attributeTypeID == 2423228754106148037712574142965102) {
return (IERC20(source).balanceOf(account) >= 1);
}
uint256 maxGas = gasleft() > 20000 ? 20000 : gasleft();
bytes memory encodedParams = abi.encodeWithSelector(
this.hasAttribute.selector,
account,
attributeTypeID
);
assembly {
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // get storage start from free memory pointer
mstore(output, 0x0) // set up the location for output of staticcall
let success := staticcall(
maxGas, // maximum of 20k gas can be forwarded
source, // address of attribute registry to call
encodedParams_data, // inputs are stored at pointer location
encodedParams_size, // inputs are 68 bytes (4 + 32 * 2)
output, // return to designated free space
0x20 // output is one word, or 32 bytes
)
switch success // instrumentation bug: use switch instead of if
case 1 { // only recognize successful staticcall output
result := mload(output) // set the output to the return value
}
}
}
} | log the addition of the attribute | emit AttributeAdded(validator, account, attributeTypeID, value);
| 1,829,717 | [
1,
1330,
326,
2719,
434,
326,
1566,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3626,
3601,
8602,
12,
7357,
16,
2236,
16,
1566,
559,
734,
16,
460,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-24
*/
// Verified using https://dapp.tools
// hevm: flattened sources of /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/AccountingEngine.sol
pragma solidity =0.6.7;
////// /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/AccountingEngine.sol
/// AccountingEngine.sol
// Copyright (C) 2018 Rain <[email protected]>
//
// 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 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity 0.6.7; */
abstract contract DebtAuctionHouseLike {
function startAuction(address incomeReceiver, uint256 amountToSell, uint256 initialBid) virtual public returns (uint256);
function protocolToken() virtual public view returns (address);
function disableContract() virtual external;
function contractEnabled() virtual public view returns (uint256);
}
abstract contract SurplusAuctionHouseLike {
function startAuction(uint256, uint256) virtual public returns (uint256);
function protocolToken() virtual public view returns (address);
function disableContract() virtual external;
function contractEnabled() virtual public view returns (uint256);
}
abstract contract SAFEEngineLike_2 {
function coinBalance(address) virtual public view returns (uint256);
function debtBalance(address) virtual public view returns (uint256);
function settleDebt(uint256) virtual external;
function transferInternalCoins(address,address,uint256) virtual external;
function approveSAFEModification(address) virtual external;
function denySAFEModification(address) virtual external;
}
abstract contract SystemStakingPoolLike {
function canPrintProtocolTokens() virtual public view returns (bool);
}
abstract contract ProtocolTokenAuthorityLike {
function authorizedAccounts(address) virtual public view returns (uint256);
}
contract AccountingEngine {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
require(contractEnabled == 1, "AccountingEngine/contract-not-enabled");
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "AccountingEngine/account-not-authorized");
_;
}
// --- Data ---
// SAFE database
SAFEEngineLike_2 public safeEngine;
// Contract that handles auctions for surplus stability fees (sell coins for protocol tokens that are then burned)
SurplusAuctionHouseLike public surplusAuctionHouse;
/**
Contract that handles auctions for debt that couldn't be covered by collateral
auctions (it prints protocol tokens in exchange for coins that will settle the debt)
**/
DebtAuctionHouseLike public debtAuctionHouse;
// Permissions registry for who can burn and mint protocol tokens
ProtocolTokenAuthorityLike public protocolTokenAuthority;
// Staking pool for protocol tokens
SystemStakingPoolLike public systemStakingPool;
// Contract that auctions extra surplus after settlement is triggered
address public postSettlementSurplusDrain;
// Address that receives extra surplus transfers
address public extraSurplusReceiver;
/**
Debt blocks that need to be covered by auctions. There is a delay to pop debt from
this queue and either settle it with surplus that came from collateral auctions or with debt auctions
that print protocol tokens
**/
mapping (uint256 => uint256) public debtQueue; // [unix timestamp => rad]
// Addresses that popped debt out of the queue
mapping (uint256 => address) public debtPoppers; // [unix timestamp => address]
// Total debt in the queue (that the system tries to cover with collateral auctions)
uint256 public totalQueuedDebt; // [rad]
// Total debt being auctioned in DebtAuctionHouse (printing protocol tokens for coins that will settle the debt)
uint256 public totalOnAuctionDebt; // [rad]
// When the last surplus auction was triggered
uint256 public lastSurplusAuctionTime; // [unix timestamp]
// When the last surplus transfer was triggered
uint256 public lastSurplusTransferTime; // [unix timestamp]
// Delay between surplus auctions
uint256 public surplusAuctionDelay; // [seconds]
// Delay between extra surplus transfers
uint256 public surplusTransferDelay; // [seconds]
// Delay after which debt can be popped from debtQueue
uint256 public popDebtDelay; // [seconds]
// Amount of protocol tokens to be minted post-auction
uint256 public initialDebtAuctionMintedTokens; // [wad]
// Amount of debt sold in one debt auction (initial coin bid for initialDebtAuctionMintedTokens protocol tokens)
uint256 public debtAuctionBidSize; // [rad]
// Whether the system transfers surplus instead of auctioning it
uint256 public extraSurplusIsTransferred;
// Amount of surplus stability fees sold in one surplus auction
uint256 public surplusAuctionAmountToSell; // [rad]
// Amount of extra surplus to transfer
uint256 public surplusTransferAmount; // [rad]
// Amount of stability fees that need to accrue in this contract before any surplus auction can start
uint256 public surplusBuffer; // [rad]
// Time to wait (post settlement) until any remaining surplus can be transferred to the settlement auctioneer
uint256 public disableCooldown; // [seconds]
// When the contract was disabled
uint256 public disableTimestamp; // [unix timestamp]
// Whether this contract is enabled or not
uint256 public contractEnabled;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 indexed parameter, uint256 data);
event ModifyParameters(bytes32 indexed parameter, address data);
event PushDebtToQueue(uint256 indexed timestamp, uint256 debtQueueBlock, uint256 totalQueuedDebt);
event PopDebtFromQueue(uint256 indexed timestamp, uint256 debtQueueBlock, uint256 totalQueuedDebt);
event SettleDebt(uint256 rad, uint256 coinBalance, uint256 debtBalance);
event CancelAuctionedDebtWithSurplus(uint rad, uint256 totalOnAuctionDebt, uint256 coinBalance, uint256 debtBalance);
event AuctionDebt(uint256 indexed id, uint256 totalOnAuctionDebt, uint256 debtBalance);
event AuctionSurplus(uint256 indexed id, uint256 lastSurplusAuctionTime, uint256 coinBalance);
event DisableContract(uint256 disableTimestamp, uint256 disableCooldown, uint256 coinBalance, uint256 debtBalance);
event TransferPostSettlementSurplus(address postSettlementSurplusDrain, uint256 coinBalance, uint256 debtBalance);
event TransferExtraSurplus(address indexed extraSurplusReceiver, uint256 lastSurplusAuctionTime, uint256 coinBalance);
// --- Init ---
constructor(
address safeEngine_,
address surplusAuctionHouse_,
address debtAuctionHouse_
) public {
authorizedAccounts[msg.sender] = 1;
safeEngine = SAFEEngineLike_2(safeEngine_);
surplusAuctionHouse = SurplusAuctionHouseLike(surplusAuctionHouse_);
debtAuctionHouse = DebtAuctionHouseLike(debtAuctionHouse_);
safeEngine.approveSAFEModification(surplusAuctionHouse_);
lastSurplusAuctionTime = now;
lastSurplusTransferTime = now;
contractEnabled = 1;
emit AddAuthorization(msg.sender);
}
// --- Math ---
function addition(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "AccountingEngine/add-overflow");
}
function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "AccountingEngine/sub-underflow");
}
function minimum(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
// --- Administration ---
/**
* @notice Modify an uint256 param
* @param parameter The name of the parameter modified
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "surplusAuctionDelay") surplusAuctionDelay = data;
else if (parameter == "surplusTransferDelay") surplusTransferDelay = data;
else if (parameter == "popDebtDelay") popDebtDelay = data;
else if (parameter == "surplusAuctionAmountToSell") surplusAuctionAmountToSell = data;
else if (parameter == "surplusTransferAmount") surplusTransferAmount = data;
else if (parameter == "extraSurplusIsTransferred") extraSurplusIsTransferred = data;
else if (parameter == "debtAuctionBidSize") debtAuctionBidSize = data;
else if (parameter == "initialDebtAuctionMintedTokens") initialDebtAuctionMintedTokens = data;
else if (parameter == "surplusBuffer") surplusBuffer = data;
else if (parameter == "lastSurplusTransferTime") {
require(data > now, "AccountingEngine/invalid-lastSurplusTransferTime");
lastSurplusTransferTime = data;
}
else if (parameter == "lastSurplusAuctionTime") {
require(data > now, "AccountingEngine/invalid-lastSurplusAuctionTime");
lastSurplusAuctionTime = data;
}
else if (parameter == "disableCooldown") disableCooldown = data;
else revert("AccountingEngine/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Modify an address param
* @param parameter The name of the parameter
* @param data New address for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
if (parameter == "surplusAuctionHouse") {
safeEngine.denySAFEModification(address(surplusAuctionHouse));
surplusAuctionHouse = SurplusAuctionHouseLike(data);
safeEngine.approveSAFEModification(data);
}
else if (parameter == "systemStakingPool") {
systemStakingPool = SystemStakingPoolLike(data);
systemStakingPool.canPrintProtocolTokens();
}
else if (parameter == "debtAuctionHouse") debtAuctionHouse = DebtAuctionHouseLike(data);
else if (parameter == "postSettlementSurplusDrain") postSettlementSurplusDrain = data;
else if (parameter == "protocolTokenAuthority") protocolTokenAuthority = ProtocolTokenAuthorityLike(data);
else if (parameter == "extraSurplusReceiver") extraSurplusReceiver = data;
else revert("AccountingEngine/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Getters ---
/*
* @notice Returns the amount of bad debt that is not in the debtQueue and is not currently handled by debt auctions
*/
function unqueuedUnauctionedDebt() public view returns (uint256) {
return subtract(subtract(safeEngine.debtBalance(address(this)), totalQueuedDebt), totalOnAuctionDebt);
}
/*
* @notify Returns a bool indicating whether the AccountingEngine can currently print protocol tokens using debt auctions
*/
function canPrintProtocolTokens() public view returns (bool) {
if (address(systemStakingPool) == address(0)) return true;
try systemStakingPool.canPrintProtocolTokens() returns (bool ok) {
return ok;
} catch(bytes memory) {
return true;
}
}
// --- Debt Queueing ---
/**
* @notice Push bad debt into a queue
* @dev Debt is locked in a queue to give the system enough time to auction collateral
* and gather surplus
* @param debtBlock Amount of debt to push
*/
function pushDebtToQueue(uint256 debtBlock) external isAuthorized {
debtQueue[now] = addition(debtQueue[now], debtBlock);
totalQueuedDebt = addition(totalQueuedDebt, debtBlock);
emit PushDebtToQueue(now, debtQueue[now], totalQueuedDebt);
}
/**
* @notice Pop a block of bad debt from the debt queue
* @dev A block of debt can be popped from the queue after popDebtDelay seconds have passed since it was
* added there
* @param debtBlockTimestamp Timestamp of the block of debt that should be popped out
*/
function popDebtFromQueue(uint256 debtBlockTimestamp) external {
require(addition(debtBlockTimestamp, popDebtDelay) <= now, "AccountingEngine/pop-debt-delay-not-passed");
require(debtQueue[debtBlockTimestamp] > 0, "AccountingEngine/null-debt-block");
totalQueuedDebt = subtract(totalQueuedDebt, debtQueue[debtBlockTimestamp]);
debtPoppers[debtBlockTimestamp] = msg.sender;
emit PopDebtFromQueue(now, debtQueue[debtBlockTimestamp], totalQueuedDebt);
debtQueue[debtBlockTimestamp] = 0;
}
// Debt settlement
/**
* @notice Destroy an equal amount of coins and bad debt
* @dev We can only destroy debt that is not locked in the queue and also not in a debt auction
* @param rad Amount of coins/debt to destroy (number with 45 decimals)
**/
function settleDebt(uint256 rad) public {
require(rad <= safeEngine.coinBalance(address(this)), "AccountingEngine/insufficient-surplus");
require(rad <= unqueuedUnauctionedDebt(), "AccountingEngine/insufficient-debt");
safeEngine.settleDebt(rad);
emit SettleDebt(rad, safeEngine.coinBalance(address(this)), safeEngine.debtBalance(address(this)));
}
/**
* @notice Use surplus coins to destroy debt that was in a debt auction
* @param rad Amount of coins/debt to destroy (number with 45 decimals)
**/
function cancelAuctionedDebtWithSurplus(uint256 rad) external {
require(rad <= totalOnAuctionDebt, "AccountingEngine/not-enough-debt-being-auctioned");
require(rad <= safeEngine.coinBalance(address(this)), "AccountingEngine/insufficient-surplus");
totalOnAuctionDebt = subtract(totalOnAuctionDebt, rad);
safeEngine.settleDebt(rad);
emit CancelAuctionedDebtWithSurplus(rad, totalOnAuctionDebt, safeEngine.coinBalance(address(this)), safeEngine.debtBalance(address(this)));
}
// Debt auction
/**
* @notice Start a debt auction (print protocol tokens in exchange for coins so that the
* system can be recapitalized)
* @dev We can only auction debt that is not already being auctioned and is not locked in the debt queue
**/
function auctionDebt() external returns (uint256 id) {
require(debtAuctionBidSize <= unqueuedUnauctionedDebt(), "AccountingEngine/insufficient-debt");
settleDebt(safeEngine.coinBalance(address(this)));
require(safeEngine.coinBalance(address(this)) == 0, "AccountingEngine/surplus-not-zero");
require(debtAuctionHouse.protocolToken() != address(0), "AccountingEngine/debt-auction-house-null-prot");
require(protocolTokenAuthority.authorizedAccounts(address(debtAuctionHouse)) == 1, "AccountingEngine/debt-auction-house-cannot-print-prot");
require(canPrintProtocolTokens(), "AccountingEngine/staking-pool-denies-printing");
totalOnAuctionDebt = addition(totalOnAuctionDebt, debtAuctionBidSize);
id = debtAuctionHouse.startAuction(address(this), initialDebtAuctionMintedTokens, debtAuctionBidSize);
emit AuctionDebt(id, totalOnAuctionDebt, safeEngine.debtBalance(address(this)));
}
// Surplus auction
/**
* @notice Start a surplus auction
* @dev We can only auction surplus if we wait at least 'surplusAuctionDelay' seconds since the last
* surplus auction trigger, if we keep enough surplus in the buffer and if there is no bad debt left to settle
**/
function auctionSurplus() external returns (uint256 id) {
require(extraSurplusIsTransferred != 1, "AccountingEngine/surplus-transfer-no-auction");
require(surplusAuctionAmountToSell > 0, "AccountingEngine/null-amount-to-auction");
settleDebt(unqueuedUnauctionedDebt());
require(
now >= addition(lastSurplusAuctionTime, surplusAuctionDelay),
"AccountingEngine/surplus-auction-delay-not-passed"
);
require(
safeEngine.coinBalance(address(this)) >=
addition(addition(safeEngine.debtBalance(address(this)), surplusAuctionAmountToSell), surplusBuffer),
"AccountingEngine/insufficient-surplus"
);
require(
unqueuedUnauctionedDebt() == 0,
"AccountingEngine/debt-not-zero"
);
require(surplusAuctionHouse.protocolToken() != address(0), "AccountingEngine/surplus-auction-house-null-prot");
lastSurplusAuctionTime = now;
lastSurplusTransferTime = now;
id = surplusAuctionHouse.startAuction(surplusAuctionAmountToSell, 0);
emit AuctionSurplus(id, lastSurplusAuctionTime, safeEngine.coinBalance(address(this)));
}
// Extra surplus transfers/surplus auction alternative
/**
* @notice Send surplus to an address as an alternative to surplus auctions
* @dev We can only transfer surplus if we wait at least 'surplusTransferDelay' seconds since the last
* transfer, if we keep enough surplus in the buffer and if there is no bad debt left to settle
**/
function transferExtraSurplus() external {
require(extraSurplusIsTransferred == 1, "AccountingEngine/surplus-auction-not-transfer");
require(extraSurplusReceiver != address(0), "AccountingEngine/null-surplus-receiver");
require(surplusTransferAmount > 0, "AccountingEngine/null-amount-to-transfer");
settleDebt(unqueuedUnauctionedDebt());
require(
now >= addition(lastSurplusTransferTime, surplusTransferDelay),
"AccountingEngine/surplus-transfer-delay-not-passed"
);
require(
safeEngine.coinBalance(address(this)) >=
addition(addition(safeEngine.debtBalance(address(this)), surplusTransferAmount), surplusBuffer),
"AccountingEngine/insufficient-surplus"
);
require(
unqueuedUnauctionedDebt() == 0,
"AccountingEngine/debt-not-zero"
);
lastSurplusTransferTime = now;
lastSurplusAuctionTime = now;
safeEngine.transferInternalCoins(address(this), extraSurplusReceiver, surplusTransferAmount);
emit TransferExtraSurplus(extraSurplusReceiver, lastSurplusTransferTime, safeEngine.coinBalance(address(this)));
}
/**
* @notice Disable this contract (normally called by Global Settlement)
* @dev When it's being disabled, the contract will record the current timestamp. Afterwards,
* the contract tries to settle as much debt as possible (if there's any) with any surplus that's
* left in the AccountingEngine
**/
function disableContract() external isAuthorized {
require(contractEnabled == 1, "AccountingEngine/contract-not-enabled");
contractEnabled = 0;
totalQueuedDebt = 0;
totalOnAuctionDebt = 0;
disableTimestamp = now;
surplusAuctionHouse.disableContract();
debtAuctionHouse.disableContract();
safeEngine.settleDebt(minimum(safeEngine.coinBalance(address(this)), safeEngine.debtBalance(address(this))));
emit DisableContract(disableTimestamp, disableCooldown, safeEngine.coinBalance(address(this)), safeEngine.debtBalance(address(this)));
}
/**
* @notice Transfer any remaining surplus after the disable cooldown has passed. Meant to be a backup in case GlobalSettlement.processSAFE
has a bug, governance doesn't have power over the system and there's still surplus left in the AccountingEngine
which then blocks GlobalSettlement.setOutstandingCoinSupply.
* @dev Transfer any remaining surplus after disableCooldown seconds have passed since disabling the contract
**/
function transferPostSettlementSurplus() external {
require(contractEnabled == 0, "AccountingEngine/still-enabled");
require(addition(disableTimestamp, disableCooldown) <= now, "AccountingEngine/cooldown-not-passed");
safeEngine.settleDebt(minimum(safeEngine.coinBalance(address(this)), safeEngine.debtBalance(address(this))));
safeEngine.transferInternalCoins(address(this), postSettlementSurplusDrain, safeEngine.coinBalance(address(this)));
emit TransferPostSettlementSurplus(
postSettlementSurplusDrain,
safeEngine.coinBalance(address(this)),
safeEngine.debtBalance(address(this))
);
}
} | --- Debt Queueing ---* @notice Push bad debt into a queue @dev Debt is locked in a queue to give the system enough time to auction collateral and gather surplus @param debtBlock Amount of debt to push/ | function pushDebtToQueue(uint256 debtBlock) external isAuthorized {
debtQueue[now] = addition(debtQueue[now], debtBlock);
totalQueuedDebt = addition(totalQueuedDebt, debtBlock);
emit PushDebtToQueue(now, debtQueue[now], totalQueuedDebt);
}
| 2,295,124 | [
1,
6062,
1505,
23602,
7530,
310,
9948,
225,
8547,
5570,
18202,
88,
1368,
279,
2389,
225,
1505,
23602,
353,
8586,
316,
279,
2389,
358,
8492,
326,
2619,
7304,
813,
358,
279,
4062,
4508,
2045,
287,
1377,
471,
11090,
5056,
10103,
225,
18202,
88,
1768,
16811,
434,
18202,
88,
358,
1817,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1817,
758,
23602,
774,
3183,
12,
11890,
5034,
18202,
88,
1768,
13,
3903,
353,
15341,
288,
203,
3639,
18202,
88,
3183,
63,
3338,
65,
273,
2719,
12,
323,
23602,
3183,
63,
3338,
6487,
18202,
88,
1768,
1769,
203,
3639,
2078,
21039,
758,
23602,
273,
2719,
12,
4963,
21039,
758,
23602,
16,
18202,
88,
1768,
1769,
203,
3639,
3626,
8547,
758,
23602,
774,
3183,
12,
3338,
16,
18202,
88,
3183,
63,
3338,
6487,
2078,
21039,
758,
23602,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface IUniswap {
// To convert DAI to ETH
function SWAPEXACTTOKENSFORETH436(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); //inject NONSTANDARD NAMING
// To convert ETH to YELD and burn it
function SWAPEXACTETHFORTOKENS487(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IERC20 {
function TOTALSUPPLY323() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF269(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE471(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE639(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM45(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER853(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL183(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER264() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA366() internal view 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;
}
}
contract Ownable is Context {
address payable private _owner;
event OWNERSHIPTRANSFERRED175(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER264();
emit OWNERSHIPTRANSFERRED175(address(0), _owner);
}
function OWNER564() public view returns (address payable) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER780() { //inject NONSTANDARD NAMING
require(ISOWNER198(), "Ownable: caller is not the owner");
_;
}
function ISOWNER198() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER264() == _owner;
}
function RENOUNCEOWNERSHIP104() public ONLYOWNER780 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED175(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP788(address payable newOwner) public ONLYOWNER780 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP70(newOwner);
}
function _TRANSFEROWNERSHIP70(address payable newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED175(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
function TOTALSUPPLY323() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF269(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER6(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER918(_MSGSENDER264(), recipient, amount);
return true;
}
function ALLOWANCE471(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE639(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, amount);
return true;
}
function TRANSFERFROM45(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER918(sender, recipient, amount);
_APPROVE444(sender, _MSGSENDER264(), _allowances[sender][_MSGSENDER264()].SUB46(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE61(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].ADD992(addedValue));
return true;
}
function DECREASEALLOWANCE74(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE444(_MSGSENDER264(), spender, _allowances[_MSGSENDER264()][spender].SUB46(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER918(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB46(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD992(amount);
emit TRANSFER853(sender, recipient, amount);
}
function _MINT980(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD992(amount);
_balances[account] = _balances[account].ADD992(amount);
emit TRANSFER853(address(0), account, amount);
}
function _BURN375(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB46(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB46(amount);
emit TRANSFER853(account, address(0), amount);
}
function _APPROVE444(address owner, address spender, uint256 amount) internal { //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 APPROVAL183(owner, spender, amount);
}
function _BURNFROM405(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN375(account, amount);
_APPROVE444(account, _MSGSENDER264(), _allowances[account][_MSGSENDER264()].SUB46(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME61() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL851() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS917() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier NONREENTRANT890() { //inject NONSTANDARD NAMING
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
library SafeMath {
function ADD992(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB46(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB46(a, b, "SafeMath: subtraction overflow");
}
function SUB46(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 MUL613(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV312(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV312(a, b, "SafeMath: division by zero");
}
function DIV312(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD928(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD928(a, b, "SafeMath: modulo by zero");
}
function MOD928(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE515(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE559(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER60(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFER6.selector, to, value));
}
function SAFETRANSFERFROM510(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.TRANSFERFROM45.selector, from, to, value));
}
function SAFEAPPROVE585(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE471(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, value));
}
function SAFEINCREASEALLOWANCE437(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE471(address(this), spender).ADD992(value);
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE12(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE471(address(this), spender).SUB46(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN106(token, abi.encodeWithSelector(token.APPROVE639.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN106(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Compound {
function MINT570 ( uint256 mintAmount ) external returns ( uint256 ); //inject NONSTANDARD NAMING
function REDEEM919(uint256 redeemTokens) external returns (uint256); //inject NONSTANDARD NAMING
function EXCHANGERATESTORED297() external view returns (uint); //inject NONSTANDARD NAMING
}
interface Fulcrum {
function MINT570(address receiver, uint256 amount) external payable returns (uint256 mintAmount); //inject NONSTANDARD NAMING
function BURN957(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); //inject NONSTANDARD NAMING
function ASSETBALANCEOF748(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
}
interface ILendingPoolAddressesProvider {
function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING
}
interface Aave {
function DEPOSIT261(address _reserve, uint256 _amount, uint16 _referralCode) external; //inject NONSTANDARD NAMING
}
interface AToken {
function REDEEM919(uint256 amount) external; //inject NONSTANDARD NAMING
}
interface IIEarnManager {
function RECOMMEND876(address _token) external view returns ( //inject NONSTANDARD NAMING
string memory choice,
uint256 capr,
uint256 iapr,
uint256 aapr,
uint256 dapr
);
}
contract Structs {
struct Val {
uint256 value;
}
enum ActionType {
Deposit, // supply tokens
Withdraw // borrow tokens
}
enum AssetDenomination {
Wei // the amount is denominated in wei
}
enum AssetReference {
Delta // the amount is given as a delta from the current value
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
contract DyDx is Structs {
function GETACCOUNTWEI173(Info memory account, uint256 marketId) public view returns (Wei memory); //inject NONSTANDARD NAMING
function OPERATE410(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING
}
interface LendingPoolAddressesProvider {
function GETLENDINGPOOL795() external view returns (address); //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE176() external view returns (address); //inject NONSTANDARD NAMING
}
contract yTUSD is ERC20, ERC20Detailed, ReentrancyGuard, Structs, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
uint256 public pool;
address public token;
address public compound;
address public fulcrum;
address public aave;
address public aavePool;
address public aaveToken;
address public dydx;
uint256 public dToken;
address public apr;
address public chai;
// Add other tokens if implemented for another stablecoin
address public uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public tusd = 0x0000000000085d4780B73119b644AE5ecd22b376;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address payable public retirementYeldTreasury;
IERC20 public yeldToken;
uint256 public maximumTokensToBurn = 50000 * 1e18;
// When you stake say 1000 TUSD for a day that will be your maximum
// if you stake the next time 300 TUSD your maximum will stay the same
// if you stake 2000 at once it will increase to 2000 TUSD
mapping(bytes32 => uint256) public numberOfParticipants;
mapping(address => uint256) public depositBlockStarts;
uint256 public constant onedayinblocks32 = 6500; //inject NONSTANDARD NAMING
uint256 public yeldToRewardPerDay = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility
uint256 public constant onemillion240 = 1e6; //inject NONSTANDARD NAMING
enum Lender {
NONE,
DYDX,
COMPOUND,
AAVE,
FULCRUM
}
Lender public provider = Lender.NONE;
constructor (address _yeldToken, address payable _retirementYeldTreasury) public payable ERC20Detailed("yearn TUSD", "yTUSD", 18) {
token = address(0x0000000000085d4780B73119b644AE5ecd22b376);
apr = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8);
dydx = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e);
aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
aavePool = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3);
fulcrum = address(0x493C57C4763932315A328269E1ADaD09653B9081);
aaveToken = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d);
compound = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643);
chai = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215);
dToken = 3;
yeldToken = IERC20(_yeldToken);
retirementYeldTreasury = _retirementYeldTreasury;
APPROVETOKEN94();
}
// To receive ETH after converting it from TUSD
function () external payable {}
function SETRETIREMENTYELDTREASURY648(address payable _treasury) public ONLYOWNER780 { //inject NONSTANDARD NAMING
retirementYeldTreasury = _treasury;
}
// In case a new uniswap router version is released
function SETUNISWAPROUTER36(address _uniswapRouter) public ONLYOWNER780 { //inject NONSTANDARD NAMING
uniswapRouter = _uniswapRouter;
}
function EXTRACTTOKENSIFSTUCK789(address _token, uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING
IERC20(_token).TRANSFER6(msg.sender, _amount);
}
function EXTRACTETHIFSTUCK584() public ONLYOWNER780 { //inject NONSTANDARD NAMING
OWNER564().transfer(address(this).balance);
}
function CHANGEYELDTOREWARDPERDAY778(uint256 _amount) public ONLYOWNER780 { //inject NONSTANDARD NAMING
yeldToRewardPerDay = _amount;
}
function GETGENERATEDYELDS438() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 blocksPassed;
if (depositBlockStarts[msg.sender] > 0) {
blocksPassed = block.number.SUB46(depositBlockStarts[msg.sender]);
} else {
blocksPassed = 0;
}
// This will work because amount is a token with 18 decimals
// Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1
// That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day
// your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since
// we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding
// For USDC and Tether gotta multiply by 1e12 since they have 6 decimals to get the proper result of YELD
uint256 ibalance = BALANCEOF269(msg.sender); // Balance of yTokens
uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply);
uint256 generatedYelds = accomulatedStablecoins.DIV312(onemillion240).MUL613(yeldToRewardPerDay.DIV312(1e18)).MUL613(blocksPassed).DIV312(onedayinblocks32);
return generatedYelds;
}
function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225() public { //inject NONSTANDARD NAMING
uint256 ibalance = BALANCEOF269(msg.sender);
uint256 accomulatedStablecoins = (CALCPOOLVALUEINTOKEN983().MUL613(ibalance)).DIV312(_totalSupply);
require(depositBlockStarts[msg.sender] > 0 && accomulatedStablecoins > 0, 'Must have deposited stablecoins beforehand');
uint256 generatedYelds = GETGENERATEDYELDS438();
depositBlockStarts[msg.sender] = block.number;
yeldToken.TRANSFER6(msg.sender, generatedYelds);
}
function DEPOSIT261(uint256 _amount) //inject NONSTANDARD NAMING
external
NONREENTRANT890
{
require(_amount > 0, "deposit must be greater than 0");
pool = CALCPOOLVALUEINTOKEN983();
IERC20(token).SAFETRANSFERFROM510(msg.sender, address(this), _amount);
// Yeld
if (GETGENERATEDYELDS438() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT225();
depositBlockStarts[msg.sender] = block.number;
// Yeld
// Calculate pool shares
uint256 shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.MUL613(_totalSupply)).DIV312(pool);
}
pool = CALCPOOLVALUEINTOKEN983();
_MINT980(msg.sender, shares);
REBALANCE90();
}
// Converts TUSD to ETH and returns how much ETH has been received from Uniswap
function TUSDTOETH442(uint256 _amount) internal returns(uint256) { //inject NONSTANDARD NAMING
IERC20(tusd).SAFEAPPROVE585(uniswapRouter, 0);
IERC20(tusd).SAFEAPPROVE585(uniswapRouter, _amount);
address[] memory path = new address[](2);
path[0] = tusd;
path[1] = weth;
// swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
// 'amounts' is an array where [0] is input TUSD amount and [1] is the resulting ETH after the conversion
// even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap
// https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth
uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTTOKENSFORETH436(_amount, uint(0), path, address(this), now.ADD992(1800));
return amounts[1];
}
// Buys YELD tokens paying in ETH on Uniswap and removes them from circulation
// Returns how many YELD tokens have been burned
function BUYNBURN597(uint256 _ethToSwap) internal returns(uint256) { //inject NONSTANDARD NAMING
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(yeldToken);
// Burns the tokens by taking them out of circulation, sending them to the 0x0 address
uint[] memory amounts = IUniswap(uniswapRouter).SWAPEXACTETHFORTOKENS487.value(_ethToSwap)(uint(0), path, address(0), now.ADD992(1800));
return amounts[1];
}
// No rebalance implementation for lower fees and faster swaps
function WITHDRAW331(uint256 _shares) //inject NONSTANDARD NAMING
external
NONREENTRANT890
{
require(_shares > 0, "withdraw must be greater than 0");
uint256 ibalance = BALANCEOF269(msg.sender);
require(_shares <= ibalance, "insufficient balance");
pool = CALCPOOLVALUEINTOKEN983();
uint256 stablecoinsToWithdraw = (pool.MUL613(_shares)).DIV312(_totalSupply);
_balances[msg.sender] = _balances[msg.sender].SUB46(_shares, "redeem amount exceeds balance");
_totalSupply = _totalSupply.SUB46(_shares);
emit TRANSFER853(msg.sender, address(0), _shares);
uint256 b = IERC20(token).BALANCEOF269(address(this));
if (b < stablecoinsToWithdraw) {
_WITHDRAWSOME967(stablecoinsToWithdraw.SUB46(b));
}
// Yeld
uint256 generatedYelds = GETGENERATEDYELDS438();
// Take 1% of the amount to withdraw
uint256 onePercent = stablecoinsToWithdraw.DIV312(100);
depositBlockStarts[msg.sender] = block.number;
yeldToken.TRANSFER6(msg.sender, generatedYelds);
// Take a portion of the profits for the buy and burn and retirement yeld
// Convert half the TUSD earned into ETH for the protocol algorithms
uint256 stakingProfits = TUSDTOETH442(onePercent);
uint256 tokensAlreadyBurned = yeldToken.BALANCEOF269(address(0));
if (tokensAlreadyBurned < maximumTokensToBurn) {
// 98% is the 49% doubled since we already took the 50%
uint256 ethToSwap = stakingProfits.MUL613(98).DIV312(100);
// Buy and burn only applies up to 50k tokens burned
BUYNBURN597(ethToSwap);
// 1% for the Retirement Yield
uint256 retirementYeld = stakingProfits.MUL613(2).DIV312(100);
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
} else {
// If we've reached the maximum burn point, send half the profits to the treasury to reward holders
uint256 retirementYeld = stakingProfits;
// Send to the treasury
retirementYeldTreasury.transfer(retirementYeld);
}
IERC20(token).SAFETRANSFER60(msg.sender, stablecoinsToWithdraw.SUB46(onePercent));
// Yeld
pool = CALCPOOLVALUEINTOKEN983();
REBALANCE90();
}
function RECOMMEND876() public view returns (Lender) { //inject NONSTANDARD NAMING
(,uint256 capr,uint256 iapr,uint256 aapr,uint256 dapr) = IIEarnManager(apr).RECOMMEND876(token);
uint256 max = 0;
if (capr > max) {
max = capr;
}
if (iapr > max) {
max = iapr;
}
if (aapr > max) {
max = aapr;
}
if (dapr > max) {
max = dapr;
}
Lender newProvider = Lender.NONE;
if (max == capr) {
newProvider = Lender.COMPOUND;
} else if (max == iapr) {
newProvider = Lender.FULCRUM;
} else if (max == aapr) {
newProvider = Lender.AAVE;
} else if (max == dapr) {
newProvider = Lender.DYDX;
}
return newProvider;
}
function GETAAVE657() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave).GETLENDINGPOOL795();
}
function GETAAVECORE248() public view returns (address) { //inject NONSTANDARD NAMING
return LendingPoolAddressesProvider(aave).GETLENDINGPOOLCORE176();
}
function APPROVETOKEN94() public { //inject NONSTANDARD NAMING
IERC20(token).SAFEAPPROVE585(compound, uint(-1));
IERC20(token).SAFEAPPROVE585(dydx, uint(-1));
IERC20(token).SAFEAPPROVE585(GETAAVECORE248(), uint(-1));
IERC20(token).SAFEAPPROVE585(fulcrum, uint(-1));
}
function BALANCE782() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(address(this));
}
function BALANCEDYDXAVAILABLE330() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(dydx);
}
function BALANCEDYDX86() public view returns (uint256) { //inject NONSTANDARD NAMING
Wei memory bal = DyDx(dydx).GETACCOUNTWEI173(Info(address(this), 0), dToken);
return bal.value;
}
function BALANCECOMPOUND355() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(compound).BALANCEOF269(address(this));
}
function BALANCECOMPOUNDINTOKEN294() public view returns (uint256) { //inject NONSTANDARD NAMING
// Mantisa 1e18 to decimals
uint256 b = BALANCECOMPOUND355();
if (b > 0) {
b = b.MUL613(Compound(compound).EXCHANGERATESTORED297()).DIV312(1e18);
}
return b;
}
function BALANCEFULCRUMAVAILABLE395() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(chai).BALANCEOF269(fulcrum);
}
function BALANCEFULCRUMINTOKEN503() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 b = BALANCEFULCRUM271();
if (b > 0) {
b = Fulcrum(fulcrum).ASSETBALANCEOF748(address(this));
}
return b;
}
function BALANCEFULCRUM271() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(fulcrum).BALANCEOF269(address(this));
}
function BALANCEAAVEAVAILABLE892() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(token).BALANCEOF269(aavePool);
}
function BALANCEAAVE873() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(aaveToken).BALANCEOF269(address(this));
}
function REBALANCE90() public { //inject NONSTANDARD NAMING
Lender newProvider = RECOMMEND876();
if (newProvider != provider) {
_WITHDRAWALL499();
}
if (BALANCE782() > 0) {
if (newProvider == Lender.DYDX) {
_SUPPLYDYDX870(BALANCE782());
} else if (newProvider == Lender.FULCRUM) {
_SUPPLYFULCRUM37(BALANCE782());
} else if (newProvider == Lender.COMPOUND) {
_SUPPLYCOMPOUND942(BALANCE782());
} else if (newProvider == Lender.AAVE) {
_SUPPLYAAVE258(BALANCE782());
}
}
provider = newProvider;
}
function _WITHDRAWALL499() internal { //inject NONSTANDARD NAMING
uint256 amount = BALANCECOMPOUND355();
if (amount > 0) {
_WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1));
}
amount = BALANCEDYDX86();
if (amount > 0) {
if (amount > BALANCEDYDXAVAILABLE330()) {
amount = BALANCEDYDXAVAILABLE330();
}
_WITHDRAWDYDX942(amount);
}
amount = BALANCEFULCRUM271();
if (amount > 0) {
if (amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) {
amount = BALANCEFULCRUMAVAILABLE395().SUB46(1);
}
_WITHDRAWSOMEFULCRUM209(amount);
}
amount = BALANCEAAVE873();
if (amount > 0) {
if (amount > BALANCEAAVEAVAILABLE892()) {
amount = BALANCEAAVEAVAILABLE892();
}
_WITHDRAWAAVE427(amount);
}
}
function _WITHDRAWSOMECOMPOUND259(uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 b = BALANCECOMPOUND355();
uint256 bT = BALANCECOMPOUNDINTOKEN294();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1);
_WITHDRAWCOMPOUND330(amount);
}
function _WITHDRAWSOMEFULCRUM209(uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 b = BALANCEFULCRUM271();
uint256 bT = BALANCEFULCRUMINTOKEN503();
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.MUL613(_amount)).DIV312(bT).ADD992(1);
_WITHDRAWFULCRUM371(amount);
}
function _WITHDRAWSOME967(uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING
uint256 origAmount = _amount;
uint256 amount = BALANCECOMPOUND355();
if (amount > 0) {
if (_amount > BALANCECOMPOUNDINTOKEN294().SUB46(1)) {
_WITHDRAWSOMECOMPOUND259(BALANCECOMPOUNDINTOKEN294().SUB46(1));
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWSOMECOMPOUND259(_amount);
return true;
}
}
amount = BALANCEDYDX86();
if (amount > 0) {
if (_amount > BALANCEDYDXAVAILABLE330()) {
_WITHDRAWDYDX942(BALANCEDYDXAVAILABLE330());
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWDYDX942(_amount);
return true;
}
}
amount = BALANCEFULCRUM271();
if (amount > 0) {
if (_amount > BALANCEFULCRUMAVAILABLE395().SUB46(1)) {
amount = BALANCEFULCRUMAVAILABLE395().SUB46(1);
_WITHDRAWSOMEFULCRUM209(BALANCEFULCRUMAVAILABLE395().SUB46(1));
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWSOMEFULCRUM209(amount);
return true;
}
}
amount = BALANCEAAVE873();
if (amount > 0) {
if (_amount > BALANCEAAVEAVAILABLE892()) {
_WITHDRAWAAVE427(BALANCEAAVEAVAILABLE892());
_amount = origAmount.SUB46(IERC20(token).BALANCEOF269(address(this)));
} else {
_WITHDRAWAAVE427(_amount);
return true;
}
}
return true;
}
function _SUPPLYDYDX870(uint256 amount) internal { //inject NONSTANDARD NAMING
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Deposit;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).OPERATE410(infos, args);
}
function _SUPPLYAAVE258(uint amount) internal { //inject NONSTANDARD NAMING
Aave(GETAAVE657()).DEPOSIT261(token, amount, 0);
}
function _SUPPLYFULCRUM37(uint amount) internal { //inject NONSTANDARD NAMING
require(Fulcrum(fulcrum).MINT570(address(this), amount) > 0, "FULCRUM: supply failed");
}
function _SUPPLYCOMPOUND942(uint amount) internal { //inject NONSTANDARD NAMING
require(Compound(compound).MINT570(amount) == 0, "COMPOUND: supply failed");
}
function _WITHDRAWAAVE427(uint amount) internal { //inject NONSTANDARD NAMING
AToken(aaveToken).REDEEM919(amount);
}
function _WITHDRAWFULCRUM371(uint amount) internal { //inject NONSTANDARD NAMING
require(Fulcrum(fulcrum).BURN957(address(this), amount) > 0, "FULCRUM: withdraw failed");
}
function _WITHDRAWCOMPOUND330(uint amount) internal { //inject NONSTANDARD NAMING
require(Compound(compound).REDEEM919(amount) == 0, "COMPOUND: withdraw failed");
}
function _WITHDRAWDYDX942(uint256 amount) internal { //inject NONSTANDARD NAMING
Info[] memory infos = new Info[](1);
infos[0] = Info(address(this), 0);
AssetAmount memory amt = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, amount);
ActionArgs memory act;
act.actionType = ActionType.Withdraw;
act.accountId = 0;
act.amount = amt;
act.primaryMarketId = dToken;
act.otherAddress = address(this);
ActionArgs[] memory args = new ActionArgs[](1);
args[0] = act;
DyDx(dydx).OPERATE410(infos, args);
}
function CALCPOOLVALUEINTOKEN983() public view returns (uint) { //inject NONSTANDARD NAMING
return BALANCECOMPOUNDINTOKEN294()
.ADD992(BALANCEFULCRUMINTOKEN503())
.ADD992(BALANCEDYDX86())
.ADD992(BALANCEAAVE873())
.ADD992(BALANCE782());
}
function GETPRICEPERFULLSHARE370() public view returns (uint) { //inject NONSTANDARD NAMING
uint _pool = CALCPOOLVALUEINTOKEN983();
return _pool.MUL613(1e18).DIV312(_totalSupply);
}
} | inject NONSTANDARD NAMING
| function SUB46(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { | 977,124 | [
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,
10025,
8749,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./mocks/MockLLTH.sol";
contract Masterdemon is Ownable, ReentrancyGuard {
using Address for address;
/**
* @notice keep track of each user and their info
*
* 'stakedTokens' => mapping of collection address and array of staked ids
* in given collection.
* 'amountStaked' => keep track of total amount of nfts staked in any pool
* 'userBalance' => somewhat unnecessary addition, to keep track of user rewards.
* this becomes always 0 after _harvest, so removing it might be a good thing.
*/
struct UserInfo {
mapping(address => uint256[]) stakedTokens;
uint256 amountStaked;
uint256 daysStaked;
uint256 userBalance;
}
/**
* @notice keep track of each collection and their info
*
* 'isStakable' => instead of deleting the collection from mapping/array,
* we use simple bool to disable it. By this we avoid possible complications
* of holes in arrays (due to lack of deleting items at index in solidity),
* sacrificing overall performance.
* 'collectionAddress' => ethereum address of given contract
* 'stakingFee' => simple msg.value
* 'harvestingFee' => simple msg.value
* 'multiplier' => boost collections by increasing rewards
* 'maturityPeriod' => represented in days, this will assure that user has to
* stake for "some time" to start accumulating rewards
* 'amountOfStakers' => amount of people in given collection, used to decrease
* rewards as collection popularity rises
* 'maxDaysForStaking' => each collection will have staking limit that will be
* represented in days. Users can stake freely before they reach this limit, then
* either they cheat thru staking from other account or they move to another pool
* 'stakingLimit' => another limitation, represented in amount of staked nfts in
* particular collection. Users can stake freely before they reach this limit and
* again, either they cheat thru staking from other account or they move to another
* pool.
*/
struct CollectionInfo {
bool isStakable;
address collectionAddress;
uint256 stakingFee;
uint256 harvestingFee;
uint256 multiplier;
uint256 maturityPeriod;
uint256 amountOfStakers;
uint256 maxDaysForStaking;
uint256 stakingLimit;
}
/**
* @notice map user addresses over their info
*/
mapping(address => UserInfo) public userInfo;
/**
* @notice colleciton address => (staked nft => user address)
* @dev would be nice if replace uint256 to uint256[]
*/
mapping(address => mapping(uint256 => address)) public tokenOwners;
/**
* @notice array of each collection, we search thru this by _cid (collection address)
*/
CollectionInfo[] public collectionInfo;
/**
@notice Lilith token
*/
MockLLTH public llth;
constructor(MockLLTH _llth) {
llth = _llth;
}
function stake(uint256 _cid, uint256 _id) external {
_stake(msg.sender, _cid, _id);
}
function batchStake(uint256 _cid, uint256[] memory _ids) external {
for (uint256 i; i < _ids.length; ++i) {
_stake(msg.sender, _cid, _ids[i]);
}
}
function unstake(uint256 _cid, uint256 _id) external {
_unstake(msg.sender, _cid, _id);
}
function batchUnstake(uint256 _cid, uint256[] memory _ids) external {
for (uint256 i; i < _ids.length; ++i) {
_unstake(msg.sender, _cid, _ids[i]);
}
}
/**
* @notice internal stake function, called in external stake and batchStake
* @param _user => msg.sender
* @param _cid => collection id, to get correct one from array
* @param _id => nft id
* - First we have to check if user reached the staking limitation.
* - We transfer their NFT to contract
* - If user never staked here before, we increment amountOfStakers
* - increment amountStaked by 1
* - Start tracking of daysStaked with timestamp
* - populate stakedTokens mapping
* - populate tokenOwners double mapping with user's address
*/
function _stake(
address _user,
uint256 _cid,
uint256 _id
) internal {
UserInfo storage user = userInfo[_user];
CollectionInfo memory collection = collectionInfo[_cid];
require(
user.stakedTokens[collection.collectionAddress].length <
collection.stakingLimit,
"Masterdemon._stake: You can't stake more"
);
IERC721(collection.collectionAddress).safeTransferFrom(
_user,
address(this),
_id
);
if (user.stakedTokens[collection.collectionAddress].length == 0) {
collection.amountOfStakers += 1;
}
user.amountStaked += 1;
user.daysStaked = block.timestamp;
user.stakedTokens[collection.collectionAddress].push(_id);
tokenOwners[collection.collectionAddress][_id] = _user;
}
/**
* @notice internal unstake function, called in external unstake and batchUnstake
* @param _user => msg.sender
* @param _cid => collection id, to get correct one from array
* @param _id => nft id
*
* - Important require statement checks if user really staked in given collection
* with help of double mapping
* - If it's okay, we return the tokens, without minting any rewards
* - Next several lines are for delicate array manipulation
* - delete id from stakedTokens mapping => array
* - delete user from tokenOwners double mapping
* - reset user's daysStaked
* - if user has nothing left in given collection, deincrement amountOfstakers
* - if user has nothing staked at all (in any collection), delete their struct
*/
function _unstake(
address _user,
uint256 _cid,
uint256 _id
) internal {
UserInfo storage user = userInfo[_user];
CollectionInfo memory collection = collectionInfo[_cid];
require(
tokenOwners[collection.collectionAddress][_id] == _user,
"Masterdemon._unstake: Sender doesn't owns this token"
);
IERC721(collection.collectionAddress).safeTransferFrom(
address(this),
_user,
_id
);
// also deletes the gaps
for (
uint256 i;
i < user.stakedTokens[collection.collectionAddress].length;
++i
) {
if (user.stakedTokens[collection.collectionAddress][i] == _id) {
delete user.stakedTokens[collection.collectionAddress][i];
user.stakedTokens[collection.collectionAddress][i] = user
.stakedTokens[collection.collectionAddress][
user.stakedTokens[collection.collectionAddress].length -
1
];
user.stakedTokens[collection.collectionAddress].pop();
}
}
// delete will leave 0x000...000
delete tokenOwners[collection.collectionAddress][_id];
user.daysStaked = 0;
if (user.stakedTokens[collection.collectionAddress].length == 0) {
collection.amountOfStakers -= 1;
}
if (user.amountStaked == 0) {
delete userInfo[_user];
}
}
/**
* @notice internal _harvest function, called in external harvest
* @param _user => msg.sender
* @param _cid => collection id
*
* - Calculating daysStaked by converting unix epoch to days (dividing on 60 / 60 / 24)
* - Collection must be stakable
* - daysStaked must be over maturityPeriod of given collection
* - daysStaked must be less than maxDaysForStaking limitation of given collection
* - To sum rewards from every single nft staked in given collection, we are looping
* thru user.stakedTokens mapping of address => array.
* - Check rarity of each token, calculate rewards and push them into user.userBalance
* - Mint rewards
* - Reset userBalance to 0.
*/
function _harvest(address _user, uint256 _cid) internal {
UserInfo storage user = userInfo[_user];
CollectionInfo memory collection = collectionInfo[_cid];
uint256 daysStaked = (block.timestamp - user.daysStaked) / 86400;
require(
collection.isStakable == true,
"Masterdemon._harvest: Staking in given pool has finished"
);
require(
daysStaked >= collection.maturityPeriod,
"Masterdemon._harvest: You can't harvest yet"
);
require(
daysStaked < collection.maxDaysForStaking,
"Masterdemon._harvest: You have reached staking period limit"
);
for (
uint256 i;
i < user.stakedTokens[collection.collectionAddress].length;
++i
) {
uint256 currentId = user.stakedTokens[collection.collectionAddress][
i
];
uint256 rarity = _getRarity(
collection.collectionAddress,
currentId
);
require(
rarity >= 50 && rarity <= 350,
"Masterdemon._harvest: Wrong range"
);
uint256 reward = _getReward(
rarity,
user.daysStaked,
collection.multiplier,
collection.amountOfStakers
);
user.userBalance += reward;
}
llth.mint(_user, user.userBalance);
user.userBalance = 0;
}
/**
* @notice dummy function, needs implementation
*/
function _getRarity(address _collectionAddress, uint256 _nftId)
internal
returns (uint256 rarity)
{
rarity = 100; // dummy
}
/**
* @notice calculate rewards of each NFT based on our formula
* {see whitepaper for clear explanation}
*/
function _getReward(
uint256 _rarity,
uint256 _daysStaked,
uint256 _multiplier,
uint256 _amountOfStakers
) internal pure returns (uint256) {
uint256 baseMultiplier = _multiplier * _daysStaked;
uint256 basemultiplierxRarity = baseMultiplier * _rarity;
uint256 finalReward = basemultiplierxRarity / _amountOfStakers;
return finalReward;
}
/**
* @notice initialize new collection
* {see struct for param definition}
*/
function setCollection(
bool _isStakable,
address _collectionAddress,
uint256 _stakingFee,
uint256 _harvestingFee,
uint256 _multiplier,
uint256 _maturityPeriod,
uint256 _maxDaysForStaking,
uint256 _stakingLimit
) public onlyOwner {
collectionInfo.push(
CollectionInfo({
isStakable: _isStakable,
collectionAddress: _collectionAddress,
stakingFee: _stakingFee,
harvestingFee: _harvestingFee,
multiplier: _multiplier,
maturityPeriod: _maturityPeriod,
amountOfStakers: 200, // notice, its for testing purposes. this should be 0 in production
maxDaysForStaking: _maxDaysForStaking,
stakingLimit: _stakingLimit
})
);
}
/**
* @notice update collection
* {see struct for param definition}
*/
function updateCollection(
uint256 _cid,
bool _isStakable,
address _collectionAddress,
uint256 _stakingFee,
uint256 _harvestingFee,
uint256 _multiplier,
uint256 _maturityPeriod,
uint256 _maxDaysForStaking,
uint256 _stakingLimit
) public onlyOwner {
CollectionInfo memory collection = collectionInfo[_cid];
collection.isStakable = _isStakable;
collection.collectionAddress = _collectionAddress;
collection.stakingFee = _stakingFee;
collection.harvestingFee = _harvestingFee;
collection.multiplier = _multiplier;
collection.maturityPeriod = _maturityPeriod;
collection.maxDaysForStaking = _maxDaysForStaking;
collection.stakingLimit = _stakingLimit;
}
/**
* @notice enable/disable collections
* @param _cid => collection id
* @param _isStakable => enable/disable
*/
function manageCollection(uint256 _cid, bool _isStakable) public onlyOwner {
CollectionInfo memory collection = collectionInfo[_cid];
collection.isStakable = _isStakable;
}
/**
* @notice stop every single collection, BE CAREFUL
* @param _confirmationPin => dummy pin to avoid "missclicking"
*/
function emergencyStop(uint256 _confirmationPin) public onlyOwner {
require(
_confirmationPin == 666,
"Masterdemon.emergencyStop: Please provide the correct pin"
);
for (uint256 i = 0; i < collectionInfo.length; ++i) {
CollectionInfo memory collection = collectionInfo[i];
if (collection.isStakable = true) {
collection.isStakable = false;
}
}
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external returns (bytes4) {
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
}
| * @notice internal _harvest function, called in external harvest @param _user => msg.sender @param _cid => collection id - Calculating daysStaked by converting unix epoch to days (dividing on 60 / 60 / 24) - Collection must be stakable - daysStaked must be over maturityPeriod of given collection - daysStaked must be less than maxDaysForStaking limitation of given collection - To sum rewards from every single nft staked in given collection, we are looping thru user.stakedTokens mapping of address => array. - Check rarity of each token, calculate rewards and push them into user.userBalance - Mint rewards - Reset userBalance to 0./ | function _harvest(address _user, uint256 _cid) internal {
UserInfo storage user = userInfo[_user];
CollectionInfo memory collection = collectionInfo[_cid];
uint256 daysStaked = (block.timestamp - user.daysStaked) / 86400;
require(
collection.isStakable == true,
"Masterdemon._harvest: Staking in given pool has finished"
);
require(
daysStaked >= collection.maturityPeriod,
"Masterdemon._harvest: You can't harvest yet"
);
require(
daysStaked < collection.maxDaysForStaking,
"Masterdemon._harvest: You have reached staking period limit"
);
for (
uint256 i;
i < user.stakedTokens[collection.collectionAddress].length;
++i
) {
uint256 currentId = user.stakedTokens[collection.collectionAddress][
i
];
uint256 rarity = _getRarity(
collection.collectionAddress,
currentId
);
require(
rarity >= 50 && rarity <= 350,
"Masterdemon._harvest: Wrong range"
);
uint256 reward = _getReward(
rarity,
user.daysStaked,
collection.multiplier,
collection.amountOfStakers
);
user.userBalance += reward;
}
llth.mint(_user, user.userBalance);
user.userBalance = 0;
}
| 7,213,409 | [
1,
7236,
389,
30250,
26923,
445,
16,
2566,
316,
3903,
17895,
26923,
377,
389,
1355,
516,
1234,
18,
15330,
377,
389,
13478,
516,
1849,
612,
565,
300,
15994,
1776,
4681,
510,
9477,
635,
14540,
9753,
7632,
358,
4681,
261,
2892,
10415,
603,
4752,
342,
4752,
342,
4248,
13,
565,
300,
2200,
1297,
506,
384,
581,
429,
565,
300,
4681,
510,
9477,
1297,
506,
1879,
29663,
5027,
434,
864,
1849,
565,
300,
4681,
510,
9477,
1297,
506,
5242,
2353,
943,
9384,
1290,
510,
6159,
17732,
434,
864,
1849,
565,
300,
2974,
2142,
283,
6397,
628,
3614,
2202,
290,
1222,
384,
9477,
316,
864,
1849,
16,
732,
854,
25004,
565,
286,
8653,
729,
18,
334,
9477,
5157,
2874,
434,
1758,
516,
526,
18,
565,
300,
2073,
436,
20498,
434,
1517,
1147,
16,
4604,
283,
6397,
471,
1817,
2182,
1368,
729,
18,
1355,
13937,
565,
300,
490,
474,
283,
6397,
565,
300,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
389,
30250,
26923,
12,
2867,
389,
1355,
16,
2254,
5034,
389,
13478,
13,
2713,
288,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
1355,
15533,
203,
3639,
2200,
966,
3778,
1849,
273,
1849,
966,
63,
67,
13478,
15533,
203,
203,
3639,
2254,
5034,
4681,
510,
9477,
273,
261,
2629,
18,
5508,
300,
729,
18,
9810,
510,
9477,
13,
342,
21451,
31,
203,
203,
3639,
2583,
12,
203,
5411,
1849,
18,
291,
510,
581,
429,
422,
638,
16,
203,
5411,
315,
7786,
323,
2586,
6315,
30250,
26923,
30,
934,
6159,
316,
864,
2845,
711,
6708,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
4681,
510,
9477,
1545,
1849,
18,
7373,
2336,
5027,
16,
203,
5411,
315,
7786,
323,
2586,
6315,
30250,
26923,
30,
4554,
848,
1404,
17895,
26923,
4671,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
4681,
510,
9477,
411,
1849,
18,
1896,
9384,
1290,
510,
6159,
16,
203,
5411,
315,
7786,
323,
2586,
6315,
30250,
26923,
30,
4554,
1240,
8675,
384,
6159,
3879,
1800,
6,
203,
3639,
11272,
203,
203,
3639,
364,
261,
203,
5411,
2254,
5034,
277,
31,
203,
5411,
277,
411,
729,
18,
334,
9477,
5157,
63,
5548,
18,
5548,
1887,
8009,
2469,
31,
203,
5411,
965,
77,
203,
3639,
262,
288,
203,
5411,
2254,
5034,
783,
548,
273,
729,
18,
334,
9477,
5157,
63,
5548,
18,
5548,
1887,
6362,
203,
7734,
277,
203,
5411,
308,
31,
203,
5411,
2254,
5034,
436,
20498,
273,
389,
588,
54,
20498,
12,
203,
7734,
1849,
18,
5548,
2
] |
./full_match/1/0x3Eb63F33eB01cb39a0ce711844FaA8b581cCbEa0/sources/contracts/Token.sol | 1% of total supply
| maxTxAmount = totalSupply / 100; | 9,816,887 | [
1,
21,
9,
434,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
943,
4188,
6275,
273,
2078,
3088,
1283,
342,
2130,
31,
540,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^ 0.4.24;
import "../scaccesscontrol/BuyerRole.sol";
import "../scaccesscontrol/ShopRole.sol";
import "../scaccesscontrol/StoreRole.sol";
import "../sccore/Ownable.sol";
// Define a contract 'Supplychain'
contract SupplyChain is BuyerRole,
ShopRole,
StoreRole,
Ownable {
// Define 'owner'
// address owner;
// Define a variable called 'sn' for Serial Number (SN)
uint sn;
// Define a variable called 'sku' for Stock Keeping Unit (SKU)
uint sku;
// Define a public mapping 'items' that maps the SN to an Item.
mapping(uint => Item) items;
// Define a public mapping 'itemsHistory' that maps the SN to an array of TxHash,
// that track its journey through the supply chain -- to be sent from DApp.
mapping(uint => string[]) itemsHistory;
// Define enum 'State' with the following values:
enum State {
Removed, // 0
CleanInspect, // 1
Shipped, // 2
Received, // 3
Inspected, // 4
Repaired, // 5
Purchased // 6
}
State constant defaultState = State.Removed;
// Define a struct 'Item' with the following fields:
struct Item
{
uint sku; // Stock Keeping Unit (SKU)
uint sn; // Serial Number (SN), recorded by the Shop, goes on the package, can be verified by the Consumer
address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 7 stages
address originShopID; // Metamask-Ethereum address of the Shop
string originShopName; // Shop Name
string originShopInformation; // Shop Information
string originShopLatitude; // Shop Latitude
string originShopLongitude; // Shop Longitude
uint productID; // Product ID potentially a combination of sn + sku //part number?
string productNotes; // Product Notes
uint productPrice; // Product Price
State itemState; // Product State as represented in the enum above
address storeID; // Metamask-Ethereum address of the Distributor
address buyerID; // Metamask-Ethereum address of the Consumer
}
// Define 7 events with the same 8 state values and accept 'sn' as input argument
event Removed(uint sn);
event CleanInspect(uint sn);
event Shipped(uint sn);
event Received(uint sn);
event Inspected(uint sn);
event Repaired(uint sn);
event Purchased(uint sn);
// Define a modifer that checks to see if msg.sender == owner of the contract
// modifier onlyOwner() {
// require(msg.sender == owner);
// _;
// }
// Define a modifer that verifies the Caller
modifier verifyCaller(address _address) {
require(msg.sender == _address);
_;
}
// Define a modifier that checks if the paid amount is sufficient to cover the price
modifier paidEnough(uint _price) {
require(msg.value >= _price);
_;
}
// Define a modifier that checks the price and refunds the remaining balance
modifier checkValue(uint _sn) {
_;
uint _price = items[_sn].productPrice;
uint amountToReturn = msg.value - _price;
items[_sn].buyerID.transfer(amountToReturn);
}
// STATE MODIFIERS
// Define a modifier that checks if an item.state of a sn is Removed
modifier removed(uint _sn) {
require(items[_sn].itemState == State.Removed);
_;
}
// Define a modifier that checks if an item.state of a sn is CleanInspect
modifier cleaninspect(uint _sn) {
require(items[_sn].itemState == State.CleanInspect);
_;
}
// Define a modifier that checks if an item.state of a sn is Shipped
modifier shipped(uint _sn) {
require(items[_sn].itemState == State.Shipped);
_;
}
// Define a modifier that checks if an item.state of a sn is Received
modifier received(uint _sn) {
require(items[_sn].itemState == State.Received);
_;
}
// Define a modifier that checks if an item.state of a sn is Inspected
modifier inspected(uint _sn) {
require(items[_sn].itemState == State.Inspected);
_;
}
// Define a modifier that checks if an item.state of a sn is Repaired
modifier repaired(uint _sn) {
require(items[_sn].itemState == State.Repaired);
_;
}
// Define a modifier that checks if an item.state of a sn is Purchased
modifier purchased(uint _sn) {
require(items[_sn].itemState == State.Purchased);
_;
}
// In the constructor set 'owner' to the address that instantiated the contract
// and set 'sku' to 1
// and set 'sn' to 1
constructor() public payable {
// owner = msg.sender;
sku = 1;
sn = 1;
}
// Define a function 'kill' if required
// function kill() public {
// if (msg.sender == owner) {
// selfdestruct(owner);
// }
// }
// Define a function 'removeItem' that allows a shop to mark an item 'Removed'
function removeItem(uint _sn, address _originShopID, string memory _originShopName, string memory _originShopInformation, string memory _originShopLatitude, string memory _originShopLongitude, string memory _productNotes) public
verifyCaller(_originShopID)
// only shop role can call this function?
{
// Check SN is new
require(items[_sn].sn == 0, "SN already exists");
// Add the new item as part of Removal
Item memory newItem;
newItem.sku = sku;
newItem.sn = _sn;
newItem.originShopID = msg.sender;
newItem.ownerID = _originShopID;
newItem.originShopName = _originShopName;
newItem.originShopInformation = _originShopInformation;
newItem.originShopLatitude = _originShopLatitude;
newItem.originShopLongitude = _originShopLongitude;
newItem.productID = _sn + sku; // add PN?
newItem.productNotes = _productNotes;
// newItem.productPrice = 0; // placeholder = to be updated following inspection?
newItem.itemState = State.Removed;
// newItem.storeID; // placeholder
// newItem.buyerID; // placeholder
// Increment sku
sku = sku + 1;
// Update mapping
items[_sn] = newItem;
// Emit the appropriate event
emit Removed(sn);
}
// Define a function 'cleanInspectItem' that allows a shop to mark an item 'CleanInspect'
function cleanInspectItem(uint _sn) public
// Call modifier to check if sn has passed previous supply chain stage (is removed)
removed(_sn)
// Call modifier to verify caller of this function
verifyCaller(items[_sn].originShopID)
{
// Update the appropriate fields
items[_sn].itemState = State.CleanInspect;
// Emit the appropriate event
emit CleanInspect(_sn);
}
// Define a function 'shipItem' that allows a shop to mark an item 'Shipped'
function shipItem(uint _sn) public
// Call modifier to check if sn has passed previous supply chain stage
cleaninspect(_sn)
// Call modifier to verify caller of this function
verifyCaller(items[_sn].originShopID)
{
// Update the appropriate fields
items[_sn].itemState = State.Shipped;
// Emit the appropriate event
emit Shipped(_sn);
}
// Define a function 'receiveItem' that allows a shop to mark an item 'Received'
function receiveItem(uint _sn, uint _price) public
// Call modifier to check if sn has passed previous supply chain stage
shipped(_sn)
// Call modifier to verify caller of this function
verifyCaller(items[_sn].originShopID)
onlyShop()
{
// Update the appropriate fields
items[_sn].itemState = State.Received;
// Emit the appropriate event
emit Received(_sn);
}
// Define a function 'inspectItem' that allows a shop to mark an item 'Inspected'
function inspectItem(uint _sn) public
// Call modifier to check if sn has passed previous supply chain stage
received(_sn)
// Call modifier to verify caller of this function
verifyCaller(items[_sn].originShopID)
{
// Update the appropriate fields
items[_sn].itemState = State.Inspected;
// Emit the appropriate event
emit Inspected(_sn);
}
// Define a function 'repairItem' that allows a shop to mark an item 'Repaired'
function repairItem(uint _sn) public
// Call modifier to check if sn has passed previous supply chain stage
inspected(_sn)
// Call modifier to verify caller of this function
verifyCaller(items[_sn].originShopID)
{
// Update the appropriate fields
items[_sn].itemState = State.Repaired;
// Emit the appropriate event
emit Repaired(_sn);
}
// Define a function 'buyItem' that allows the store to mark an item 'Purchased'
// Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough,
// and any excess ether sent is refunded back to the buyer
function buyItem(uint _sn) public payable
// Call modifier to check if sn has passed previous supply chain stage
repaired(_sn)
// Call modifer to check if buyer has paid enough
paidEnough(items[_sn].productPrice)
// Call modifer to send any excess ether back to buyer
checkValue(_sn)
{
// Update the appropriate fields - ownerID, storeID, itemState
items[_sn].ownerID = msg.sender;
items[_sn].buyerID = msg.sender;
items[_sn].itemState = State.Purchased;
// Transfer money to shop
items[_sn].storeID.transfer(items[_sn].productPrice);
// emit the appropriate event
emit Purchased(_sn);
}
// Define a function 'fetchItemBufferOne' that fetches the data
function fetchItemBufferOne(uint _sn) public view returns
(
uint itemSKU,
uint itemSN,
address ownerID,
address originShopID,
string originShopName,
string originShopInformation,
string originShopLatitude,
string originShopLongitude
)
{
itemSKU = items[_sn].sku;
itemSN = items[_sn].sn;
ownerID = items[_sn].ownerID;
originShopID = items[_sn].originShopID;
originShopName = items[_sn].originShopName;
originShopInformation = items[_sn].originShopInformation;
originShopLatitude = items[_sn].originShopLatitude;
originShopLongitude = items[_sn].originShopLongitude;
return
(
itemSKU,
itemSN,
ownerID,
originShopID,
originShopName,
originShopInformation,
originShopLatitude,
originShopLongitude
);
}
// Define a function 'fetchItemBufferTwo' that fetches the data
function fetchItemBufferTwo(uint _sn) public view returns
(
uint itemSKU,
uint itemSN,
uint productID,
string productNotes,
uint productPrice,
State itemState,
address storeID,
address buyerID
)
{
itemSKU = items[_sn].sku;
itemSN = items[_sn].sn;
productID = items[_sn].productID;
productNotes = items[_sn].productNotes;
productPrice = items[_sn].productPrice;
itemState = items[_sn].itemState;
storeID = items[_sn].storeID;
buyerID = items[_sn].buyerID;
return
(
itemSKU,
itemSN,
productID,
productNotes,
productPrice,
itemState,
storeID,
buyerID
);
}
}
| Stock Keeping Unit (SKU)
| uint sku; | 1,760,842 | [
1,
17821,
10498,
310,
8380,
261,
11129,
57,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
565,
16731,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// 'DYF Token' Smart Contract
//
// OwnerAddress :
// Symbol :
// Name :
// Total Supply :
// Decimals : 18
// Copyrights of 'DYFToken' With 'DYF' Symbol October 25, 2020.
// The MIT Licence.
//
// Prepared and Compiled by: HASSAN ISA
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// Ownership contract
// _newOwner is address of new owner
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = 0x0D6B9AD91B86194c3BaE4cC3DB7ab466EC164048;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// transfer Ownership to other address
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
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);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract DYFToken is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public RATE;
uint public DENOMINATOR;
bool public isStopped = false;
mapping(address =>uint) balances;
mapping(address => mapping(address =>uint)) allowed;
event Mint(address indexed to, uint256 amount);
event ChangeRate(uint256 amount);
modifier onlyWhenRunning {
require(!isStopped);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "DYF";
name = "DeFi Yearn Fiinance";
decimals = 18;
_totalSupply = 30000 * 10**uint(decimals);
balances[owner] = _totalSupply;
RATE = 20000; // 1 ETH = 20 DYF
DENOMINATOR = 1000;
emit Transfer(address(0), owner, _totalSupply);
}
// ----------------------------------------------------------------------------
// requires enough gas for execution
// ----------------------------------------------------------------------------
function() public payable {
buyTokens();
}
// ----------------------------------------------------------------------------
// Function to handle eth and token transfers
// tokens are transferred to user
// ETH are transferred to current owner
// ----------------------------------------------------------------------------
function buyTokens() onlyWhenRunning public payable {
require(msg.value> 0);
uint tokens = msg.value.mul(RATE).div(DENOMINATOR);
require(balances[owner] >= tokens);
balances[msg.sender] = balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
emit Transfer(owner, msg.sender, tokens);
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view 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) {
require(to != address(0));
require(tokens > 0);
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
require(spender != address(0));
require(tokens > 0);
allowed[msg.sender][spender] = tokens;
emit 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
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(from != address(0));
require(to != address(0));
require(tokens > 0);
require(balances[from] >= tokens);
require(allowed[from][msg.sender] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit 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 view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// 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)
// _spender The address which will spend the funds.
// _addedValueThe amount of tokens to increase the allowance by.
// ------------------------------------------------------------------------
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// ------------------------------------------------------------------------
// 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)
// _spender The address which will spend the funds.
// _subtractedValueThe amount of tokens to decrease the allowance by.
// ------------------------------------------------------------------------
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(_spender != address(0));
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;
}
// ------------------------------------------------------------------------
// Change the ETH to IO rate
// ------------------------------------------------------------------------
function changeRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
RATE =_rate;
emit ChangeRate(_rate);
}
// ------------------------------------------------------------------------
// _to The address that will receive the minted tokens.
// _amount The amount of tokens to mint.
// A boolean that indicates if the operation was successful.
// ------------------------------------------------------------------------
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
require(_to != address(0));
require(_amount > 0);
uint newamount = _amount * 10**uint(decimals);
_totalSupply = _totalSupply.add(newamount);
balances[_to] = balances[_to].add(newamount);
emit Mint(_to, newamount);
emit Transfer(address(0), _to, newamount);
return true;
}
// ------------------------------------------------------------------------
// function to stop the ICO
// ------------------------------------------------------------------------
function stopPRESALE() onlyOwner public {
isStopped = true;
}
// ------------------------------------------------------------------------
// function to resume PRESALE
// ------------------------------------------------------------------------
function resumePRESALE() onlyOwner public {
isStopped = false;
}
} | ------------------------------------------------------------------------ Total supply ------------------------------------------------------------------------ | function totalSupply() public view returns (uint) {
return _totalSupply;
}
| 1,245,682 | [
1,
29461,
10710,
14467,
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,
0,
0,
0,
0,
0,
0,
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,
915,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
2463,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xE6cC6bf6c404fCe83aDdcC0c3dEB58b669fEE70E/sources/localhost/exchange/wrappers/UniswapWrapper.sol | @notice Buys a _destAmount of tokens at Uniswap @param _srcAddr From token @param _destAddr To token @param _destAmount To amount @return uint srcAmount if we are selling ether if we are buying ether if we are buying token to token | function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint) {
address uniswapExchangeAddr;
uint srcAmount;
if (_srcAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr);
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
}
else if (_destAddr == WETH_ADDRESS) {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).approve(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender);
}
else {
uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr);
ERC20(_srcAddr).approve(uniswapExchangeAddr, uint(-1));
srcAmount = UniswapExchangeInterface(uniswapExchangeAddr).
tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr);
}
return srcAmount;
}
| 16,467,087 | [
1,
38,
89,
1900,
279,
389,
10488,
6275,
434,
2430,
622,
1351,
291,
91,
438,
225,
389,
4816,
3178,
6338,
1147,
225,
389,
10488,
3178,
2974,
1147,
225,
389,
10488,
6275,
2974,
3844,
327,
2254,
1705,
6275,
309,
732,
854,
357,
2456,
225,
2437,
309,
732,
854,
30143,
310,
225,
2437,
309,
732,
854,
30143,
310,
1147,
358,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
30143,
12,
2867,
389,
4816,
3178,
16,
1758,
389,
10488,
3178,
16,
2254,
389,
10488,
6275,
13,
3903,
8843,
429,
1135,
12,
11890,
13,
288,
203,
3639,
1758,
640,
291,
91,
438,
11688,
3178,
31,
203,
3639,
2254,
1705,
6275,
31,
203,
203,
3639,
309,
261,
67,
4816,
3178,
422,
678,
1584,
44,
67,
15140,
13,
288,
203,
5411,
640,
291,
91,
438,
11688,
3178,
273,
1351,
291,
91,
438,
1733,
1358,
12,
2124,
5127,
59,
2203,
67,
16193,
2934,
588,
11688,
24899,
10488,
3178,
1769,
203,
203,
5411,
1705,
6275,
273,
1351,
291,
91,
438,
11688,
1358,
12,
318,
291,
91,
438,
11688,
3178,
2934,
203,
3639,
289,
203,
3639,
469,
309,
261,
67,
10488,
3178,
422,
678,
1584,
44,
67,
15140,
13,
288,
203,
5411,
640,
291,
91,
438,
11688,
3178,
273,
1351,
291,
91,
438,
1733,
1358,
12,
2124,
5127,
59,
2203,
67,
16193,
2934,
588,
11688,
24899,
4816,
3178,
1769,
203,
203,
5411,
4232,
39,
3462,
24899,
4816,
3178,
2934,
12908,
537,
12,
318,
291,
91,
438,
11688,
3178,
16,
2254,
19236,
21,
10019,
203,
203,
5411,
1705,
6275,
273,
1351,
291,
91,
438,
11688,
1358,
12,
318,
291,
91,
438,
11688,
3178,
2934,
203,
7734,
1147,
774,
41,
451,
5912,
1447,
24899,
10488,
6275,
16,
2254,
19236,
21,
3631,
1203,
18,
5508,
397,
404,
16,
1234,
18,
15330,
1769,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
640,
291,
91,
438,
11688,
3178,
273,
1351,
291,
91,
438,
1733,
1358,
12,
2124,
5127,
59,
2203,
67,
2
] |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./BatchAction.sol";
import "./nTokenRedeemAction.sol";
import "./ActionGuards.sol";
import "../FreeCollateralExternal.sol";
import "../../global/StorageLayoutV1.sol";
import "../../math/SafeInt256.sol";
import "../../internal/AccountContextHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "interfaces/IERC1155TokenReceiver.sol";
import "interfaces/notional/nERC1155Interface.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/utils/Address.sol";
contract ERC1155Action is nERC1155Interface, ActionGuards {
using SafeInt256 for int256;
using AccountContextHandler for AccountContext;
bytes4 internal constant ERC1155_ACCEPTED = bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
bytes4 internal constant ERC1155_BATCH_ACCEPTED = bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));
function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
return interfaceId == type(IERC1155).interfaceId;
}
/// @notice Returns the balance of an ERC1155 id on an account. WARNING: the balances returned by
/// this method do not show negative fCash balances because only unsigned integers are returned. They
/// are represented by zero here. Use `signedBalanceOf` to get a signed return value.
/// @param account account to get the id for
/// @param id the ERC1155 id
/// @return Balance of the ERC1155 id as an unsigned integer (negative fCash balances return zero)
function balanceOf(address account, uint256 id) public view override returns (uint256) {
int256 notional = signedBalanceOf(account, id);
return notional < 0 ? 0 : notional.toUint();
}
/// @notice Returns the balance of an ERC1155 id on an account.
/// @param account account to get the id for
/// @param id the ERC1155 id
/// @return notional balance of the ERC1155 id as a signed integer
function signedBalanceOf(address account, uint256 id) public view override returns (int256 notional) {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.isBitmapEnabled()) {
notional = _balanceInBitmap(account, accountContext.bitmapCurrencyId, id);
} else {
notional = _balanceInArray(
PortfolioHandler.getSortedPortfolio(account, accountContext.assetArrayLength),
id
);
}
}
/// @notice Returns the balance of a batch of accounts and ids.
/// @param accounts array of accounts to get balances for
/// @param ids array of ids to get balances for
/// @return Returns an array of signed balances
function signedBalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
override
returns (int256[] memory)
{
require(accounts.length == ids.length);
int256[] memory amounts = new int256[](accounts.length);
for (uint256 i; i < accounts.length; i++) {
// This is pretty inefficient but gets the job done
amounts[i] = signedBalanceOf(accounts[i], ids[i]);
}
return amounts;
}
/// @notice Returns the balance of a batch of accounts and ids. WARNING: negative fCash balances are represented
/// as zero balances in the array.
/// @param accounts array of accounts to get balances for
/// @param ids array of ids to get balances for
/// @return Returns an array of unsigned balances
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length);
uint256[] memory amounts = new uint256[](accounts.length);
for (uint256 i; i < accounts.length; i++) {
// This is pretty inefficient but gets the job done
amounts[i] = balanceOf(accounts[i], ids[i]);
}
return amounts;
}
/// @dev Returns the balance from a bitmap given the id
function _balanceInBitmap(
address account,
uint256 bitmapCurrencyId,
uint256 id
) internal view returns (int256) {
(uint256 currencyId, uint256 maturity, uint256 assetType) = TransferAssets.decodeAssetId(id);
if (
currencyId != bitmapCurrencyId ||
assetType != Constants.FCASH_ASSET_TYPE
) {
// Neither of these are possible for a bitmap group
return 0;
} else {
return BitmapAssetsHandler.getifCashNotional(account, currencyId, maturity);
}
}
/// @dev Searches an array for the matching asset
function _balanceInArray(PortfolioAsset[] memory portfolio, uint256 id)
internal
pure
returns (int256)
{
(uint256 currencyId, uint256 maturity, uint256 assetType) = TransferAssets.decodeAssetId(id);
for (uint256 i; i < portfolio.length; i++) {
PortfolioAsset memory asset = portfolio[i];
if (
asset.currencyId == currencyId &&
asset.maturity == maturity &&
asset.assetType == assetType
) return asset.notional;
}
}
/// @notice Transfer of a single fCash or liquidity token asset between accounts. Allows `from` account to transfer more fCash
/// than they have as long as they pass a subsequent free collateral check. This enables OTC trading of fCash assets.
/// @param from account to transfer from
/// @param to account to transfer to
/// @param id ERC1155 id of the asset
/// @param amount amount to transfer
/// @param data arbitrary data passed to ERC1155Receiver (if contract) and if properly specified can be used to initiate
/// a trading action on Notional for the `from` address
/// @dev emit:TransferSingle, emit:AccountContextUpdate, emit:AccountSettled
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external payable override {
// NOTE: there is no re-entrancy guard on this method because that would prevent a callback in
// _checkPostTransferEvent. The external call to the receiver is done at the very end after all stateful
// updates have occurred.
_validateAccounts(from, to);
// When amount is set to zero this method can be used as a way to execute trades via a transfer operator
AccountContext memory fromContext;
if (amount > 0) {
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
PortfolioAsset memory asset = assets[0];
(asset.currencyId, asset.maturity, asset.assetType) = TransferAssets.decodeAssetId(id);
// This ensures that asset.notional is always a positive amount
asset.notional = SafeInt256.toInt(amount);
_requireValidMaturity(asset.currencyId, asset.maturity, block.timestamp);
// prettier-ignore
(fromContext, /* toContext */) = _transfer(from, to, assets);
emit TransferSingle(msg.sender, from, to, id, amount);
} else {
fromContext = AccountContextHandler.getAccountContext(from);
}
// toContext is always empty here because we cannot have bidirectional transfers in `safeTransferFrom`
AccountContext memory toContext;
_checkPostTransferEvent(from, to, fromContext, toContext, data, false);
// Do this external call at the end to prevent re-entrancy
if (Address.isContract(to)) {
require(
IERC1155TokenReceiver(to).onERC1155Received(msg.sender, from, id, amount, data) ==
ERC1155_ACCEPTED,
"Not accepted"
);
}
}
/// @notice Transfer of a batch of fCash or liquidity token assets between accounts. Allows `from` account to transfer more fCash
/// than they have as long as they pass a subsequent free collateral check. This enables OTC trading of fCash assets.
/// @param from account to transfer from
/// @param to account to transfer to
/// @param ids ERC1155 ids of the assets
/// @param amounts amounts to transfer
/// @param data arbitrary data passed to ERC1155Receiver (if contract) and if properly specified can be used to initiate
/// a trading action on Notional for the `from` address
/// @dev emit:TransferBatch, emit:AccountContextUpdate, emit:AccountSettled
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external payable override {
// NOTE: there is no re-entrancy guard on this method because that would prevent a callback in
// _checkPostTransferEvent. The external call to the receiver is done at the very end.
_validateAccounts(from, to);
(PortfolioAsset[] memory assets, bool toTransferNegative) = _decodeToAssets(ids, amounts);
// When doing a bidirectional transfer must ensure that the `to` account has given approval
// to msg.sender as well.
if (toTransferNegative) require(isApprovedForAll(to, msg.sender), "Unauthorized");
(AccountContext memory fromContext, AccountContext memory toContext) = _transfer(
from,
to,
assets
);
_checkPostTransferEvent(from, to, fromContext, toContext, data, toTransferNegative);
emit TransferBatch(msg.sender, from, to, ids, amounts);
// Do this at the end to prevent re-entrancy
if (Address.isContract(to)) {
require(
IERC1155TokenReceiver(to).onERC1155BatchReceived(
msg.sender,
from,
ids,
amounts,
data
) == ERC1155_BATCH_ACCEPTED,
"Not accepted"
);
}
}
/// @dev Validates accounts on transfer
function _validateAccounts(address from, address to) private view {
// Cannot transfer to self, cannot transfer to zero address
require(from != to && to != address(0) && to != address(this), "Invalid address");
// Authentication is valid
require(msg.sender == from || isApprovedForAll(from, msg.sender), "Unauthorized");
// nTokens will not accept transfers because they do not implement the ERC1155
// receive method
// Defensive check to ensure that an authorized operator does not call these methods
// with an invalid `from` account
requireValidAccount(from);
}
/// @notice Decodes ids and amounts to PortfolioAsset objects
/// @param ids array of ERC1155 ids
/// @param amounts amounts to transfer
/// @return array of portfolio asset objects
function decodeToAssets(uint256[] calldata ids, uint256[] calldata amounts)
external
view
override
returns (PortfolioAsset[] memory)
{
// prettier-ignore
(PortfolioAsset[] memory assets, /* */) = _decodeToAssets(ids, amounts);
return assets;
}
function _decodeToAssets(uint256[] calldata ids, uint256[] calldata amounts)
internal
view
returns (PortfolioAsset[] memory, bool)
{
require(ids.length == amounts.length);
bool toTransferNegative = false;
PortfolioAsset[] memory assets = new PortfolioAsset[](ids.length);
for (uint256 i; i < ids.length; i++) {
// Require that ids are not duplicated, there is no valid reason to have duplicate ids
if (i > 0) require(ids[i] > ids[i - 1], "IDs must be sorted");
PortfolioAsset memory asset = assets[i];
(asset.currencyId, asset.maturity, asset.assetType) = TransferAssets.decodeAssetId(ids[i]);
_requireValidMaturity(asset.currencyId, asset.maturity, block.timestamp);
// Although amounts is encoded as uint256 we allow it to be negative here. This will
// allow for bidirectional transfers of fCash. Internally fCash assets are always stored
// as int128 (for bitmap portfolio) or int88 (for array portfolio) so there is no potential
// that a uint256 value that is greater than type(int256).max would actually valid.
asset.notional = int256(amounts[i]);
// If there is a negative transfer we mark it as such, this will force us to do a free collateral
// check on the `to` address as well.
if (asset.notional < 0) toTransferNegative = true;
}
return (assets, toTransferNegative);
}
/// @notice Encodes parameters into an ERC1155 id
/// @param currencyId currency id of the asset
/// @param maturity timestamp of the maturity
/// @param assetType id of the asset type
/// @return ERC1155 id
function encodeToId(
uint16 currencyId,
uint40 maturity,
uint8 assetType
) external pure override returns (uint256) {
return TransferAssets.encodeAssetId(currencyId, maturity, assetType);
}
/// @dev Ensures that all maturities specified are valid for the currency id (i.e. they do not
/// go past the max maturity date)
function _requireValidMaturity(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private view {
require(
DateTime.isValidMaturity(CashGroup.getMaxMarketIndex(currencyId), maturity, blockTime),
"Invalid maturity"
);
}
/// @dev Internal asset transfer event between accounts
function _transfer(
address from,
address to,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory, AccountContext memory) {
// Finalize all parts of a transfer for each account separately. Settlement must happen
// before the call to placeAssetsInAccount so that we load the proper portfolio state.
AccountContext memory toContext = AccountContextHandler.getAccountContext(to);
if (toContext.mustSettleAssets()) {
toContext = SettleAssetsExternal.settleAccount(to, toContext);
}
toContext = TransferAssets.placeAssetsInAccount(to, toContext, assets);
toContext.setAccountContext(to);
// Will flip the sign of notional in the assets array in memory
TransferAssets.invertNotionalAmountsInPlace(assets);
// Now finalize the from account
AccountContext memory fromContext = AccountContextHandler.getAccountContext(from);
if (fromContext.mustSettleAssets()) {
fromContext = SettleAssetsExternal.settleAccount(from, fromContext);
}
fromContext = TransferAssets.placeAssetsInAccount(from, fromContext, assets);
fromContext.setAccountContext(from);
return (fromContext, toContext);
}
/// @dev Checks post transfer events which will either be initiating one of the batch trading events or a free collateral
/// check if required.
function _checkPostTransferEvent(
address from,
address to,
AccountContext memory fromContext,
AccountContext memory toContext,
bytes calldata data,
bool toTransferNegative
) internal {
bytes4 sig = 0;
address transactedAccount = address(0);
if (data.length >= 32) {
// Method signature is not abi encoded so decode to bytes32 first and take the first 4 bytes. This works
// because all the methods we want to call below require more than 32 bytes in the calldata
bytes32 tmp = abi.decode(data, (bytes32));
sig = bytes4(tmp);
}
// These are the only three methods allowed to occur in a post transfer event. These actions allow `from`
// accounts to take any sort of trading action as a result of their transfer. All of these actions will
// handle checking free collateral so no additional check is necessary here.
if (
sig == nTokenRedeemAction.nTokenRedeem.selector ||
sig == BatchAction.batchBalanceAction.selector ||
sig == BatchAction.batchBalanceAndTradeAction.selector
) {
transactedAccount = abi.decode(data[4:36], (address));
// Ensure that the "transactedAccount" parameter of the call is set to the from address or the
// to address. If it is the "to" address then ensure that the msg.sender has approval to
// execute operations
require(
transactedAccount == from ||
(transactedAccount == to && isApprovedForAll(to, msg.sender)),
"Unauthorized call"
);
// We can only call back to Notional itself at this point, account context is already
// stored and all three of the whitelisted methods above will check free collateral.
(bool status, bytes memory result) = address(this).call{value: msg.value}(data);
require(status, _getRevertMsg(result));
}
// The transacted account will have its free collateral checked above so there is
// no need to recheck here.
// If transactedAccount == 0 then will check fc
// If transactedAccount == to then will check fc
// If transactedAccount == from then will skip, prefer call above
if (transactedAccount != from && fromContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(from);
}
// Check free collateral if the `to` account has taken on a negative fCash amount
// If toTransferNegative is false then will not check
// If transactedAccount == 0 then will check fc
// If transactedAccount == from then will check fc
// If transactedAccount == to then will skip, prefer call above
if (toTransferNegative && transactedAccount != to && toContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(to);
}
}
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows an account to set approval for an operator
/// @param operator address of the operator
/// @param approved state of the approval
/// @dev emit:ApprovalForAll
function setApprovalForAll(address operator, bool approved) external override {
accountAuthorizedTransferOperator[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/// @notice Checks approval state for an account, will first check if global transfer operator is enabled
/// before falling through to an account specific transfer operator.
/// @param account address of the account
/// @param operator address of the operator
/// @return true for approved
function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
if (globalTransferOperator[operator]) return true;
return accountAuthorizedTransferOperator[account][operator];
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction(address(this)).nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nTokenHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../external/FreeCollateralExternal.sol";
import "../../external/SettleAssetsExternal.sol";
import "../../math/SafeInt256.sol";
import "./ActionGuards.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract nTokenRedeemAction is ActionGuards {
using SafeInt256 for int256;
using SafeMath for uint256;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold. This method can only be invoked via delegatecall.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @dev auth:only internal
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
// Only self call allowed
require(msg.sender == address(this), "Unauthorized caller");
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Allows accounts to redeem nTokens into constituent assets and then absorb the assets
/// into their portfolio. Due to the complexity here, it is not allowed to be called during a batch trading
/// operation and must be done separately.
/// @param redeemer the address that holds the nTokens to redeem
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem_ the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then
/// residual fCash assets will be placed into the portfolio
/// @dev auth:msg.sender auth:ERC1155
/// @return total amount of asset cash redeemed
function nTokenRedeem(
address redeemer,
uint16 currencyId,
uint96 tokensToRedeem_,
bool sellTokenAssets
) external nonReentrant returns (int256) {
// ERC1155 can call this method during a post transfer event
require(msg.sender == redeemer || msg.sender == address(this), "Unauthorized caller");
uint256 blockTime = block.timestamp;
int256 tokensToRedeem = int256(tokensToRedeem_);
AccountContext memory context = AccountContextHandler.getAccountContext(redeemer);
if (context.mustSettleAssets()) {
context = SettleAssetsExternal.settleAccount(redeemer, context);
}
BalanceState memory balance;
balance.loadBalanceState(redeemer, currencyId, context);
require(balance.storedNTokenBalance >= tokensToRedeem, "Insufficient tokens");
balance.netNTokenSupplyChange = tokensToRedeem.neg();
(int256 totalAssetCash, bool hasResidual, PortfolioAsset[] memory assets) =
_redeem(currencyId, tokensToRedeem, sellTokenAssets, blockTime);
// Set balances before transferring assets
balance.netCashChange = totalAssetCash;
balance.finalize(redeemer, context, false);
if (hasResidual) {
// This method will store assets and update the account context in memory
context = TransferAssets.placeAssetsInAccount(redeemer, context, assets);
}
context.setAccountContext(redeemer);
if (context.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(redeemer);
}
emit nTokenSupplyChange(redeemer, currencyId, balance.netNTokenSupplyChange);
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @return assetCash: positive amount of asset cash to the account
/// @return hasResidual: true if there are fCash residuals left
/// @return assets: an array of fCash asset residuals to place into the account
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
uint256 blockTime
)
private
returns (
int256,
bool,
PortfolioAsset[] memory
)
{
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "PT: requires settlement");
// Get the assetCash and fCash assets as a result of redeeming tokens
(PortfolioAsset[] memory newfCashAssets, int256 totalAssetCash) =
_reduceTokenAssets(nToken, tokensToRedeem, blockTime);
// hasResidual is set to true if fCash assets need to be put back into the redeemer's portfolio
bool hasResidual = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: newfCashAssets is modified in place during this method
(assetCash, hasResidual) = _sellfCashAssets(
nToken.cashGroup,
newfCashAssets,
blockTime
);
totalAssetCash = totalAssetCash.add(assetCash);
}
return (totalAssetCash, hasResidual, newfCashAssets);
}
/// @notice Removes nToken assets
/// @return newifCashAssets: an array of fCash assets the redeemer will take
/// @return assetCash: amount of cash the redeemer will take
function _reduceTokenAssets(
nTokenPortfolio memory nToken,
int256 tokensToRedeem,
uint256 blockTime
) private returns (PortfolioAsset[] memory, int256) {
// Get share of ifCash assets to remove
PortfolioAsset[] memory newifCashAssets =
BitmapAssetsHandler.reduceifCashAssetsProportional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply
);
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive.
int256 assetCashShare = nToken.cashBalance.mul(tokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, newifCashAssets is modified in memory
// during this method.
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(
nToken,
newifCashAssets,
tokensToRedeem,
nToken.totalSupply,
blockTime
)
);
{
// prettier-ignore
(
/* hasDebt */,
/* currencies */,
uint8 newStorageLength,
/* nextSettleTime */
) = nToken.portfolioState.storeAssets(nToken.tokenAddress);
// This can happen if a liquidity token is redeemed down to zero. It's possible that due to dust amounts
// one token is reduced down to a zero balance while the others still have some amount remaining. In this case
// the mint nToken will fail in `addLiquidityToMarket`, an account must accept redeeming part of their
// nTokens and leaving some dust amount behind.
require(
nToken.portfolioState.storedAssets.length == uint256(newStorageLength),
"Cannot redeem to zero"
);
}
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return (newifCashAssets, assetCashShare);
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
PortfolioAsset[] memory newifCashAssets,
int256 tokensToRedeem,
int256 totalSupply,
uint256 blockTime
) private returns (int256 totalAssetCash) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
int256 tokensToRemove = asset.notional.mul(tokensToRedeem).div(totalSupply);
asset.notional = asset.notional.sub(tokensToRemove);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
// Remove liquidity from the market
(int256 assetCash, int256 fCash) = market.removeLiquidity(tokensToRemove);
totalAssetCash = totalAssetCash.add(assetCash);
// It is improbable but possible that an fcash asset does not exist if the fCash position for an active liquidity token
// is zero. This would occur when the nToken has done a lot of lending instead of providing liquidity to the point
// where the fCash position is exactly zero. This is highly unlikely so instead of adding more logic to handle it we will just
// fail here. Minting some amount of nTokens will cause the fCash position to be reinstated.
{
uint256 ifCashIndex;
while (newifCashAssets[ifCashIndex].maturity != asset.maturity) {
ifCashIndex += 1;
require(ifCashIndex < newifCashAssets.length, "Error removing tokens");
}
newifCashAssets[ifCashIndex].notional = newifCashAssets[ifCashIndex].notional.add(
fCash
);
}
}
return totalAssetCash;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
CashGroupParameters memory cashGroup,
PortfolioAsset[] memory fCashAssets,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
for (uint256 i = 0; i < fCashAssets.length; i++) {
PortfolioAsset memory asset = fCashAssets[i];
if (asset.notional == 0) continue;
(uint256 marketIndex, bool isIdiosyncratic) = DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
asset.maturity,
blockTime
);
if (isIdiosyncratic) {
hasResidual = true;
} else {
cashGroup.loadMarket(market, marketIndex, false, blockTime);
int256 netAssetCash = market.executeTrade(
cashGroup,
// Use the negative of fCash notional here since we want to net it out
asset.notional.neg(),
asset.maturity.sub(blockTime),
marketIndex
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
asset.notional = 0;
}
}
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @dev Returns the multiplication of two signed integers, reverting on
/// overflow.
/// Counterpart to Solidity's `*` operator.
/// Requirements:
/// - Multiplication cannot overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed integers. Reverts on
/// division by zero. The result is rounded towards zero.
/// Counterpart to Solidity's `/` operator. 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(int256 a, int256 b) internal pure returns (int256 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Sets the account context of a given account
function enableBitmapForAccount(
AccountContext memory accountContext,
address account,
uint16 currencyId,
uint256 blockTime
) internal view {
// Allow setting the currency id to zero to turn off bitmap
require(currencyId <= Constants.MAX_CURRENCIES, "AC: invalid currency id");
if (isBitmapEnabled(accountContext)) {
// Account cannot change their bitmap if they have assets set
bytes32 ifCashBitmap =
BitmapAssetsHandler.getAssetsBitmap(account, accountContext.bitmapCurrencyId);
require(ifCashBitmap == 0, "AC: cannot have assets");
} else {
require(accountContext.assetArrayLength == 0, "AC: cannot have assets");
// Account context also cannot have negative cash debts
require(accountContext.hasDebt == 0x00, "AC: cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
}
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../external/SettleAssetsExternal.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface IERC1155TokenReceiver {
/**
@notice Handle the receipt of a single ERC1155 token type.
@dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the
end of a `safeTransferFrom` after the balance has been updated.
This function 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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../contracts/global/Types.sol";
interface nERC1155Interface {
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
function balanceOf(address account, uint256 id) external view returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
function signedBalanceOf(address account, uint256 id) external view returns (int256);
function signedBalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (int256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external payable;
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external payable;
function decodeToAssets(uint256[] calldata ids, uint256[] calldata amounts)
external
view
returns (PortfolioAsset[] memory);
function encodeToId(
uint16 currencyId,
uint40 maturity,
uint8 assetType
) external pure returns (uint256 id);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* lastClaimIntegralSupply */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nTokenHandler.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nToken.getNTokenAssetPV(blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return Returns two values:
/// - assetAmountInternal which is the converted asset amount accounting for transfer fees
/// - assetAmountTransferred which is the internal precision amount transferred into the account
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Tokens that are not mintable like cTokens will be deposited as assetTokens
require(assetToken.tokenType == TokenType.cToken || assetToken.tokenType == TokenType.cETH); // dev: deposit underlying token invalid token type
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// It's crucial that incentives are claimed before we do any sort of nToken transfer to prevent gaming
// of the system. This method will update the lastClaimTime time and lastIntegralTotalSupply in balance
// state in place.
Incentives.claimIncentives(balanceState, account);
// nTokens are within the notional system so we can update balances directly.
balanceState.storedNTokenBalance = balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.lastClaimIntegralSupply
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// underlyingAmountExternal is converted from uint to int inside redeem, must be positive
int256 underlyingAmountExternal = assetToken.redeem(
underlyingToken,
uint256(assetTransferAmountExternal.neg())
);
// Withdraws the underlying amount out to the destination account
actualTransferAmountExternal = underlyingToken.transfer(
account,
underlyingAmountExternal.neg()
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
actualTransferAmountExternal = assetToken.transfer(account, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 lastClaimIntegralSupply) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
lastClaimIntegralSupply
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
lastClaimIntegralSupply
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
require(lastClaimTime <= type(uint32).max); // dev: last claim time overflow
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.cashBalance = int88(cashBalance);
// Last claim supply is stored in a "floating point" storage slot that does not maintain exact precision but
// is also not limited by storage overflows. `packTo56Bits` will ensure that the the returned value will fit
// in 56 bits (7 bytes)
balanceStorage.packedLastClaimIntegralSupply = FloatingPoint56.packTo56Bits(lastClaimIntegralSupply);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
lastClaimIntegralSupply = FloatingPoint56.unpackFrom56Bits(balanceStorage.packedLastClaimIntegralSupply);
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.lastClaimIntegralSupply
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.lastClaimIntegralSupply = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the lastClaimTime and lastClaimIntegralSupply
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256)
{
uint256 incentivesClaimed = Incentives.claimIncentives(balanceState, account);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.lastClaimIntegralSupply
);
return incentivesClaimed;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `buildMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(blockTime != 0 && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// 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-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* lastClaimIntegralSupply */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nToken.getNTokenAssetPV(blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* lastClaimIntegralSupply */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
nTokenTotalSupply,
AssetRate,
ExchangeRate
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function _getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) private view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = _getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 nextSettleTime,
int256 tokensToRedeem,
int256 totalSupply
) internal returns (PortfolioAsset[] memory) {
// It is not possible to redeem the entire token supply because some liquidity tokens must remain
// in the liquidity token portfolio in order to re-initialize markets.
require(tokensToRedeem < totalSupply, "Cannot redeem");
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "interfaces/chainlink/AggregatorV2V3Interface.sol";
import "interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// The last integral supply amount when tokens were claimed
uint256 lastClaimIntegralSupply;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// The total integral supply of the nToken at the last claim time packed into
// 56 bits. There is some loss of precision here but it is acceptable
uint56 packedLastClaimIntegralSupply;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 lastClaimIntegralSupply;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// NOTE: this address is hardcoded in the library, must update this on deployment
address constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 96 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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.6.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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nTokenHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @dev Notional incentivizes nTokens using the formula:
/// incentivesToClaim = (tokenBalance / totalSupply) * emissionRatePerYear * proRataYears
/// where proRataYears is:
/// (timeSinceLastClaim / YEAR) * INTERNAL_TOKEN_PRECISION
/// @return (emissionRatePerYear * proRataYears), decimal basis is (1e8 * 1e8 = 1e16)
function _getIncentiveRate(uint256 timeSinceLastClaim, uint256 emissionRatePerYear)
private
pure
returns (uint256)
{
// (timeSinceLastClaim * INTERNAL_TOKEN_PRECISION) / YEAR
uint256 proRataYears =
timeSinceLastClaim.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)).div(Constants.YEAR);
return proRataYears.mul(emissionRatePerYear);
}
/// @notice Calculates the claimable incentives for a particular nToken and account
function calculateIncentivesToClaim(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply,
uint256 blockTime,
uint256 integralTotalSupply
) internal view returns (uint256) {
if (lastClaimTime == 0 || lastClaimTime >= blockTime) return 0;
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
// No overflow here, checked above
uint256 timeSinceLastClaim = blockTime - lastClaimTime;
uint256 incentiveRate =
_getIncentiveRate(
timeSinceLastClaim,
// Convert this to the appropriate denomination, emissionRatePerYear is denominated
// in whole tokens
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
);
// Returns the average supply between now and the previous mint time using the integral of the total
// supply.
uint256 avgTotalSupply = integralTotalSupply.sub(lastClaimIntegralSupply).div(timeSinceLastClaim);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
/// @notice Incentives must be claimed every time nToken balance changes
function claimIncentives(BalanceState memory balanceState, address account)
internal
returns (uint256)
{
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will set the new supply and return the previous integral total supply
uint256 integralTotalSupply = nTokenHandler.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
uint256 incentivesToClaim = calculateIncentivesToClaim(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
balanceState.lastClaimIntegralSupply,
blockTime,
integralTotalSupply
);
balanceState.lastClaimTime = blockTime;
balanceState.lastClaimIntegralSupply = integralTotalSupply;
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
return incentivesToClaim;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "interfaces/compound/CErc20Interface.sol";
import "interfaces/compound/CEtherInterface.sol";
import "interfaces/IEIP20NonStandard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken) {
// Set the approval for the underlying so that we can mint cTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
tokenStorage.tokenAddress,
type(uint256).max
);
checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/// @notice This method only works with cTokens, it's unclear how we can make this more generic
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 startingBalance = IERC20(token.tokenAddress).balanceOf(address(this));
uint256 success;
if (token.tokenType == TokenType.cToken) {
success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
} else if (token.tokenType == TokenType.cETH) {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
} else {
revert(); // dev: non mintable token
}
require(success == Constants.COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
uint256 endingBalance = IERC20(token.tokenAddress).balanceOf(address(this));
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 startingBalance;
if (assetToken.tokenType == TokenType.cETH) {
startingBalance = address(this).balance;
} else if (assetToken.tokenType == TokenType.cToken) {
startingBalance = IERC20(underlyingToken.tokenAddress).balanceOf(address(this));
} else {
revert(); // dev: non redeemable failure
}
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == Constants.COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance;
if (assetToken.tokenType == TokenType.cETH) {
endingBalance = address(this).balance;
} else {
endingBalance = IERC20(underlyingToken.tokenAddress).balanceOf(address(this));
}
// Underlying token external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
int256 netTransferExternal
) internal returns (int256) {
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
netTransferExternal = _deposit(token, account, uint256(netTransferExternal));
} else if (token.tokenType == TokenType.Ether) {
require(netTransferExternal <= 0); // dev: cannot deposit ether
address payable accountPayable = payable(account);
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
accountPayable.transfer(uint256(netTransferExternal.neg()));
} else {
safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
return netTransferExternal;
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
if (token.hasTransferFee) {
startingBalance = IERC20(token.tokenAddress).balanceOf(address(this));
}
safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
endingBalance = IERC20(token.tokenAddress).balanceOf(address(this));
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
safeTransferOut(Constants.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) private {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) private {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() private pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./markets/CashGroup.sol";
import "./markets/AssetRate.sol";
import "./valuation/AssetHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
import "./balances/BalanceHandler.sol";
import "../math/SafeInt256.sol";
library nTokenHandler {
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// TODO: how many storage reads is this?
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Retrieves the nToken supply factors without any updates or calculations
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 integralTotalSupply,
uint256 lastSupplyChangeTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The integral total supply
// must be updated given the block time. Use `calculateIntegralTotalSupply` instead
integralTotalSupply = nTokenStorage.integralTotalSupply;
lastSupplyChangeTime = nTokenStorage.lastSupplyChangeTime;
}
/// @notice Retrieves stored total supply factors and
function calculateIntegralTotalSupply(address tokenAddress, uint256 blockTime)
internal
view
returns (
uint256 totalSupply,
uint256 integralTotalSupply,
uint256 lastSupplyChangeTime
)
{
(
totalSupply,
integralTotalSupply,
lastSupplyChangeTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// Initialize last supply change time if it has not been set.
if (lastSupplyChangeTime == 0) lastSupplyChangeTime = blockTime;
require(blockTime >= lastSupplyChangeTime); // dev: invalid block time
// Add to the integral total supply the total supply of tokens multiplied by the time that the total supply
// has been the value. This will part of the numerator for the average total supply calculation during
// minting incentives.
integralTotalSupply = uint256(int256(integralTotalSupply).add(
int256(totalSupply).mul(int256(blockTime - lastSupplyChangeTime))
));
require(integralTotalSupply >= 0 && integralTotalSupply < type(uint128).max); // dev: integral total supply overflow
require(blockTime < type(uint32).max); // dev: last supply change supply overflow
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 integralTotalSupply,
/* uint256 lastSupplyChangeTime */
) = calculateIntegralTotalSupply(tokenAddress, blockTime);
if (netChange != 0) {
// If the totalSupply will change then we store the new total supply, the integral total supply and the
// current block time. We know that this int256 conversion will not overflow because totalSupply is stored
// as a uint96 and checked in the next line.
int256 newTotalSupply = int256(totalSupply).add(netChange);
require(newTotalSupply >= 0 && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflows checked in calculateIntegralTotalSupply
nTokenStorage.integralTotalSupply = uint128(integralTotalSupply);
nTokenStorage.lastSupplyChangeTime = uint32(blockTime);
}
return integralTotalSupply;
}
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* integralTotalSupply */,
/* lastSupplyChangeTime */
) = getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* lastClaimIntegralSupply */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// Since we are not doing a risk adjusted valuation here we do not need to net off residual fCash
// balances in the future before discounting to present. If we did, then the ifCash assets would
// have to be in the portfolio array first. PV here is denominated in asset cash terms, not in
// underlying terms.
{
MarketParameters memory market;
for (uint256 i; i < nToken.portfolioState.storedAssets.length; i++) {
// NOTE: getLiquidityTokenValue can rewrite fCash values in memory, however, that does not
// happen in this call because there are no fCash values in the nToken portfolio.
(int256 assetCashClaim, int256 pv) =
AssetHandler.getLiquidityTokenValue(
i,
nToken.cashGroup,
market,
nToken.portfolioState.storedAssets,
blockTime,
false
);
totalAssetPV = totalAssetPV.add(assetCashClaim);
totalUnderlyingPV = totalUnderlyingPV.add(pv);
}
}
// Then iterate over bitmapped assets and get present value
// prettier-ignore
(
int256 bitmapPv,
/* hasDebt */
) = BitmapAssetsHandler.getifCashNetPresentValue(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false
);
totalUnderlyingPV = totalUnderlyingPV.add(bitmapPv);
// Return the total present value denominated in asset terms
totalAssetPV = totalAssetPV
.add(nToken.cashGroup.assetRate.convertFromUnderlying(totalUnderlyingPV))
.add(nToken.cashBalance);
return totalAssetPV;
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external;
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// 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: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// 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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
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 uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// 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 Checks approval state for an account, will first check if global transfer operator is enabled before falling through to an account specific transfer operator. @param account address of the account @param operator address of the operator @return true for approved | function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
if (globalTransferOperator[operator]) return true;
return accountAuthorizedTransferOperator[account][operator];
}
| 1,749,915 | [
1,
4081,
23556,
919,
364,
392,
2236,
16,
903,
1122,
866,
309,
2552,
7412,
3726,
353,
3696,
1865,
31678,
3059,
358,
392,
2236,
2923,
7412,
3726,
18,
225,
2236,
1758,
434,
326,
2236,
225,
3726,
1758,
434,
326,
3726,
327,
638,
364,
20412,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
31639,
1290,
1595,
12,
2867,
2236,
16,
1758,
3726,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
309,
261,
6347,
5912,
5592,
63,
9497,
5717,
327,
638,
31,
203,
203,
3639,
327,
2236,
15341,
5912,
5592,
63,
4631,
6362,
9497,
15533,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.16;
contract EmpresaConsulta {
struct Empresa {
bytes32 empCIF;
bytes32 nombre;
}
// This is a namespace where we will store EmpresaConsulta
mapping(bytes32 => Empresa) public empresas;
// Set values in storage
function storeEmpresa(bytes32 key, bytes32 _empCIF, bytes32 _nombre) returns (bool success) {
empresas[key].empCIF = _empCIF;
empresas[key].nombre = _nombre;
return true;
}
}
contract Otra {
EmpresaConsulta empresaconsulta;
// Define the Type in this context
struct Empresa {
bytes32 empCIF;
bytes32 nombre;
}
// For this to work, pass in D's address to E's constructor
function extraer(address empresaDir) {
empresaconsulta = EmpresaConsulta(empresaDir);
}
function retrieveData(bytes32 key)
public
constant
returns(bytes32, bytes32)
{
// Declare a temporary "doc" to hold a DocumentStruct
Empresa memory doc;
// Get it from the "public" mapping's free getter.
(doc.empCIF, doc.nombre) = empresaconsulta.empresas(key);
// return values with a fixed sized layout
return (doc.empCIF, doc.nombre);
}
}
| Set values in storage | function storeEmpresa(bytes32 key, bytes32 _empCIF, bytes32 _nombre) returns (bool success) {
empresas[key].empCIF = _empCIF;
empresas[key].nombre = _nombre;
return true;
}
| 1,036,121 | [
1,
694,
924,
316,
2502,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1707,
41,
1291,
455,
69,
12,
3890,
1578,
498,
16,
1731,
1578,
389,
30752,
39,
5501,
16,
1731,
1578,
389,
12306,
6073,
13,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
801,
12202,
345,
63,
856,
8009,
30752,
39,
5501,
273,
389,
30752,
39,
5501,
31,
203,
3639,
801,
12202,
345,
63,
856,
8009,
12306,
6073,
273,
389,
12306,
6073,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.11;
// Voken Shareholders Contract for Voken2.0
//
// More info:
// https://vision.network
// https://voken.io
//
// Contact us:
// [email protected]
// [email protected]
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
*/
library SafeMath256 {
/**
* @dev Returns the addition of two unsigned integers, reverting on 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).
*/
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).
*/
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.
*/
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. Reverts on
* division by zero. The result is rounded towards 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.
*/
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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by 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.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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];
}
}
/**
* @dev Interface of the ERC20 standard
*/
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface of an allocation contract
*/
interface IAllocation {
function reservedOf(address account) external view returns (uint256);
}
/**
* @dev Interface of Voken2.0
*/
interface IVoken2 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function mintWithAllocation(address account, uint256 amount, address allocationContract) external returns (bool);
}
/**
* @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.
*/
contract Ownable {
address internal _owner;
address internal _newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipAccepted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the addresses of the current and new owner.
*/
function owner() public view returns (address currentOwner, address newOwner) {
currentOwner = _owner;
newOwner = _newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(msg.sender), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner(address account) public view returns (bool) {
return account == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*
* IMPORTANT: Need to run {acceptOwnership} by the new owner.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_newOwner = newOwner;
}
/**
* @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 Accept ownership of the contract.
*
* Can only be called by the new owner.
*/
function acceptOwnership() public {
require(msg.sender == _newOwner, "Ownable: caller is not the new owner address");
require(msg.sender != address(0), "Ownable: caller is the zero address");
emit OwnershipAccepted(_owner, msg.sender);
_owner = msg.sender;
_newOwner = address(0);
}
/**
* @dev Rescue compatible ERC20 Token
*
* Can only be called by the current owner.
*/
function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner {
IERC20 _token = IERC20(tokenAddr);
require(recipient != address(0), "Rescue: recipient is the zero address");
uint256 balance = _token.balanceOf(address(this));
require(balance >= amount, "Rescue: amount exceeds balance");
_token.transfer(recipient, amount);
}
/**
* @dev Withdraw Ether
*
* Can only be called by the current owner.
*/
function withdrawEther(address payable recipient, uint256 amount) external onlyOwner {
require(recipient != address(0), "Withdraw: recipient is the zero address");
uint256 balance = address(this).balance;
require(balance >= amount, "Withdraw: amount exceeds balance");
recipient.transfer(amount);
}
}
/**
* @title Voken Shareholders
*/
contract VokenShareholders is Ownable, IAllocation {
using SafeMath256 for uint256;
using Roles for Roles.Role;
IVoken2 private _VOKEN = IVoken2(0xFfFAb974088Bd5bF3d7E6F522e93Dd7861264cDB);
Roles.Role private _proxies;
uint256 private _ALLOCATION_TIMESTAMP = 1598918399; // Sun, 30 Aug 2020 23:59:59 +0000
uint256 private _ALLOCATION_INTERVAL = 1 days;
uint256 private _ALLOCATION_STEPS = 60;
uint256 private _page;
uint256 private _weis;
uint256 private _vokens;
address[] private _shareholders;
mapping (address => bool) private _isShareholder;
mapping (address => uint256) private _withdrawPos;
mapping (uint256 => address[]) private _pageShareholders;
mapping (uint256 => mapping (address => bool)) private _isPageShareholder;
mapping (uint256 => uint256) private _pageEndingBlock;
mapping (uint256 => uint256) private _pageEthers;
mapping (uint256 => uint256) private _pageVokens;
mapping (uint256 => uint256) private _pageVokenSum;
mapping (uint256 => mapping (address => uint256)) private _pageVokenHoldings;
mapping (uint256 => mapping (address => uint256)) private _pageEtherDividends;
mapping (address => uint256) private _allocations;
event ProxyAdded(address indexed account);
event ProxyRemoved(address indexed account);
event Dividend(address indexed account, uint256 amount, uint256 page);
/**
* @dev Throws if called by account which is not a proxy.
*/
modifier onlyProxy() {
require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role");
_;
}
/**
* @dev Returns true if the `account` has the Proxy role.
*/
function isProxy(address account) public view returns (bool) {
return _proxies.has(account);
}
/**
* @dev Give an `account` access to the Proxy role.
*
* Can only be called by the current owner.
*/
function addProxy(address account) public onlyOwner {
_proxies.add(account);
emit ProxyAdded(account);
}
/**
* @dev Remove an `account` access from the Proxy role.
*
* Can only be called by the current owner.
*/
function removeProxy(address account) public onlyOwner {
_proxies.remove(account);
emit ProxyRemoved(account);
}
/**
* @dev Returns the VOKEN main contract address.
*/
function VOKEN() public view returns (IVoken2) {
return _VOKEN;
}
/**
* @dev Returns the max page number.
*/
function page() public view returns (uint256) {
return _page;
}
/**
* @dev Returns the amount of deposited Ether.
*/
function weis() public view returns (uint256) {
return _weis;
}
/**
* @dev Returns the amount of VOKEN holding by all shareholders.
*/
function vokens() public view returns (uint256) {
return _vokens;
}
/**
* @dev Returns the shareholders list on `pageNumber`.
*/
function shareholders(uint256 pageNumber) public view returns (address[] memory) {
if (pageNumber > 0) {
return _pageShareholders[pageNumber];
}
return _shareholders;
}
/**
* @dev Returns the shareholders counter on `pageNumber`.
*/
function shareholdersCounter(uint256 pageNumber) public view returns (uint256) {
if (pageNumber > 0) {
return _pageShareholders[pageNumber].length;
}
return _shareholders.length;
}
/**
* @dev Returns the amount of deposited Ether at `pageNumber`.
*/
function pageEther(uint256 pageNumber) public view returns (uint256) {
return _pageEthers[pageNumber];
}
/**
* @dev Returns the amount of deposited Ether till `pageNumber`.
*/
function pageEtherSum(uint256 pageNumber) public view returns (uint256) {
uint256 __page = _pageNumber(pageNumber);
uint256 __amount;
for (uint256 i = 1; i <= __page; i++) {
__amount = __amount.add(_pageEthers[i]);
}
return __amount;
}
/**
* @dev Returns the amount of VOKEN holding by all shareholders at `pageNumber`.
*/
function pageVoken(uint256 pageNumber) public view returns (uint256) {
return _pageVokens[pageNumber];
}
/**
* @dev Returns the amount of VOKEN holding by all shareholders till `pageNumber`.
*/
function pageVokenSum(uint256 pageNumber) public view returns (uint256) {
return _pageVokenSum[_pageNumber(pageNumber)];
}
/**
* Returns the ending block number of `pageNumber`.
*/
function pageEndingBlock(uint256 pageNumber) public view returns (uint256) {
return _pageEndingBlock[pageNumber];
}
/**
* Returns the page number greater than 0 by `pageNmber`.
*/
function _pageNumber(uint256 pageNumber) internal view returns (uint256) {
if (pageNumber > 0) {
return pageNumber;
}
else {
return _page;
}
}
/**
* @dev Returns the amount of VOKEN holding by `account` and `pageNumber`.
*/
function vokenHolding(address account, uint256 pageNumber) public view returns (uint256) {
uint256 __page;
uint256 __amount;
if (pageNumber > 0) {
__page = pageNumber;
}
else {
__page = _page;
}
for (uint256 i = 1; i <= __page; i++) {
__amount = __amount.add(_pageVokenHoldings[i][account]);
}
return __amount;
}
/**
* @dev Returns the ether dividend of `account` on `pageNumber`.
*/
function etherDividend(address account, uint256 pageNumber) public view returns (uint256 amount,
uint256 dividend,
uint256 remain) {
if (pageNumber > 0) {
amount = pageEther(pageNumber).mul(vokenHolding(account, pageNumber)).div(pageVokenSum(pageNumber));
dividend = _pageEtherDividends[pageNumber][account];
}
else {
for (uint256 i = 1; i <= _page; i++) {
uint256 __pageEtherDividend = pageEther(i).mul(vokenHolding(account, i)).div(pageVokenSum(i));
amount = amount.add(__pageEtherDividend);
dividend = dividend.add(_pageEtherDividends[i][account]);
}
}
remain = amount.sub(dividend);
}
/**
* @dev Returns the allocation of `account`.
*/
function allocation(address account) public view returns (uint256) {
return _allocations[account];
}
/**
* @dev Returns the reserved amount of VOKENs by `account`.
*/
function reservedOf(address account) public view returns (uint256 reserved) {
reserved = _allocations[account];
if (now > _ALLOCATION_TIMESTAMP && reserved > 0) {
uint256 __passed = now.sub(_ALLOCATION_TIMESTAMP).div(_ALLOCATION_INTERVAL).add(1);
if (__passed > _ALLOCATION_STEPS) {
reserved = 0;
}
else {
reserved = reserved.sub(reserved.mul(__passed).div(_ALLOCATION_STEPS));
}
}
}
/**
* @dev Constructor
*/
constructor () public {
_page = 1;
addProxy(msg.sender);
}
/**
* @dev {Deposit} or {Withdraw}
*/
function () external payable {
// deposit
if (msg.value > 0) {
_weis = _weis.add(msg.value);
_pageEthers[_page] = _pageEthers[_page].add(msg.value);
}
// withdraw
else if (_isShareholder[msg.sender]) {
uint256 __vokenHolding;
for (uint256 i = 1; i <= _page.sub(1); i++) {
__vokenHolding = __vokenHolding.add(_pageVokenHoldings[i][msg.sender]);
if (_withdrawPos[msg.sender] < i) {
uint256 __etherAmount = _pageEthers[i].mul(__vokenHolding).div(_pageVokenSum[i]);
_withdrawPos[msg.sender] = i;
_pageEtherDividends[i][msg.sender] = __etherAmount;
msg.sender.transfer(__etherAmount);
emit Dividend(msg.sender, __etherAmount, i);
}
}
}
assert(true);
}
/**
* @dev End the current page.
*/
function endPage() public onlyProxy {
require(_pageEthers[_page] > 0, "Ethers on current page is zero.");
_pageEndingBlock[_page] = block.number;
_page = _page.add(1);
_pageVokenSum[_page] = _vokens;
assert(true);
}
/**
* @dev Push shareholders.
*
* Can only be called by a proxy.
*/
function pushShareholders(address[] memory accounts, uint256[] memory values) public onlyProxy {
require(accounts.length == values.length, "Shareholders: batch length is not match");
for (uint256 i = 0; i < accounts.length; i++) {
address __account = accounts[i];
uint256 __value = values[i];
if (!_isShareholder[__account]) {
_shareholders.push(__account);
_isShareholder[__account] = true;
}
if (!_isPageShareholder[_page][__account]) {
_pageShareholders[_page].push(__account);
_isPageShareholder[_page][__account] = true;
}
_vokens = _vokens.add(__value);
_pageVokens[_page] = _pageVokens[_page].add(__value);
_pageVokenSum[_page] = _vokens;
_pageVokenHoldings[_page][__account] = _pageVokenHoldings[_page][__account].add(__value);
_allocations[__account] = _allocations[__account].add(__value);
assert(_VOKEN.mintWithAllocation(__account, __value, address(this)));
}
assert(true);
}
}
| Sun, 30 Aug 2020 23:59:59 +0000
| uint256 private _ALLOCATION_TIMESTAMP = 1598918399; | 12,667,721 | [
1,
29636,
16,
5196,
432,
637,
26599,
20,
10213,
30,
6162,
30,
6162,
397,
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,
565,
2254,
5034,
3238,
389,
1013,
15277,
67,
17201,
273,
4711,
29,
6675,
31672,
2733,
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
] |
pragma solidity ^0.6.12;
// ----------------------------------------------------------------------------
// DreamFrames Crowdsale Contract - Purchase FrameRush Tokens with ETH
//
// Deployed to : {TBA}
//
// Enjoy.
//
// (c) BokkyPooBah / Bok Consulting Pty Ltd for GazeCoin 2018. The MIT Licence.
// (c) Adrian Guerrera / Deepyr Pty Ltd for Dreamframes 2019. The MIT Licence.
// ----------------------------------------------------------------------------
import "../Shared/Operated.sol";
import "../Shared/SafeMath.sol";
import "../../interfaces/BTTSTokenInterface120.sol";
import "../../interfaces/PriceFeedInterface.sol";
import "../../interfaces/WhiteListInterface.sol";
// ----------------------------------------------------------------------------
// DreamFramesToken Crowdsale Contract
// ----------------------------------------------------------------------------
contract DreamFramesCrowdsale is Operated {
using SafeMath for uint256;
uint256 private constant TENPOW18 = 10 ** 18;
BTTSTokenInterface public dreamFramesToken;
PriceFeedInterface public ethUsdPriceFeed;
WhiteListInterface public bonusList;
address payable public wallet;
uint256 public startDate;
uint256 public endDate;
uint256 public producerPct;
uint256 public frameUsd;
uint256 public framesSold;
bool public finalised;
uint256 public bonusOffList;
uint256 public bonusOnList;
uint256 public contributedUsd;
uint256 public softCapUsd;
uint256 public hardCapUsd;
uint256 public lockedAccountThresholdUsd;
mapping(address => uint256) public accountUsdAmount;
event WalletUpdated(address indexed oldWallet, address indexed newWallet);
event StartDateUpdated(uint256 oldStartDate, uint256 newStartDate);
event EndDateUpdated(uint256 oldEndDate, uint256 newEndDate);
event FrameUsdUpdated(uint256 oldFrameUsd, uint256 newFrameUsd);
event BonusOffListUpdated(uint256 oldBonusOffList, uint256 newBonusOffList);
event BonusOnListUpdated(uint256 oldBonusOnList, uint256 newBonusOnList);
event BonusListUpdated(address oldBonusList, address newBonusList);
event Purchased(address indexed addr, uint256 frames, uint256 ethToTransfer, uint256 framesSold, uint256 contributedUsd);
constructor() public {
}
/// @notice
function init(address _dreamFramesToken, address _ethUsdPriceFeed, address payable _wallet, uint256 _startDate, uint256 _endDate, uint256 _producerPct, uint256 _frameUsd, uint256 _bonusOffList,uint256 _bonusOnList, uint256 _hardCapUsd, uint256 _softCapUsd) public {
require(_wallet != address(0));
require(_endDate > _startDate);
require(_startDate >= now);
require(_producerPct < 100);
require(_dreamFramesToken != address(0));
require(_ethUsdPriceFeed != address(0) );
initOperated(msg.sender);
dreamFramesToken = BTTSTokenInterface(_dreamFramesToken);
ethUsdPriceFeed = PriceFeedInterface(_ethUsdPriceFeed);
lockedAccountThresholdUsd = 10000;
hardCapUsd = _hardCapUsd;
softCapUsd = _softCapUsd;
frameUsd = _frameUsd;
wallet = _wallet;
startDate = _startDate;
endDate = _endDate;
producerPct = _producerPct;
bonusOffList = _bonusOffList;
bonusOnList = _bonusOnList;
}
// ----------------------------------------------------------------------------
// Setter functions
// ----------------------------------------------------------------------------
function setWallet(address payable _wallet) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_wallet != address(0));
emit WalletUpdated(wallet, _wallet);
wallet = _wallet;
}
function setStartDate(uint256 _startDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_startDate >= now); // dev: Already started
emit StartDateUpdated(startDate, _startDate);
startDate = _startDate;
}
function setEndDate(uint256 _endDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(endDate >= now); // dev: Already ended
require(_endDate > startDate); // dev: End before the start
emit EndDateUpdated(endDate, _endDate);
endDate = _endDate;
}
function setFrameUsd(uint256 _frameUsd) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_frameUsd > 0); // dev: Frame eq 0
emit FrameUsdUpdated(frameUsd, _frameUsd);
frameUsd = _frameUsd;
}
function setBonusOffList(uint256 _bonusOffList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOffList < 100); // dev: Bonus over 100
emit BonusOffListUpdated(bonusOffList, _bonusOffList);
bonusOffList = _bonusOffList;
}
function setBonusOnList(uint256 _bonusOnList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOnList < 100); // dev: Bonus over 100
emit BonusOnListUpdated(bonusOnList, _bonusOnList);
bonusOnList = _bonusOnList;
}
function setBonusList(address _bonusList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
emit BonusListUpdated(address(bonusList), _bonusList);
bonusList = WhiteListInterface(_bonusList);
}
// ----------------------------------------------------------------------------
// Getter functions
// ----------------------------------------------------------------------------
function symbol() public view returns (string memory _symbol) {
_symbol = dreamFramesToken.symbol();
}
function name() public view returns (string memory _name) {
_name = dreamFramesToken.name();
}
function usdRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd);
}
function pctSold() public view returns (uint256) {
return contributedUsd.mul(100).div(hardCapUsd);
}
function pctRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd).mul(100).div(hardCapUsd);
}
function getBonus(address _address) public view returns (uint256) {
if (bonusList.isInWhiteList(_address) && bonusOnList > bonusOffList ) {
return bonusOnList;
}
return bonusOffList;
}
/// @notice USD per frame, with bonus
/// @dev e.g., 128.123412344122 * 10^18
function frameUsdWithBonus(address _address) public view returns (uint256 _rate) {
uint256 bonus = getBonus(_address);
_rate = frameUsd.mul(100).div(bonus.add(100));
}
/// @notice USD per Eth from price feed
/// @dev e.g., 171.123232454415 * 10^18
function ethUsd() public view returns (uint256 _rate, bool _live) {
return ethUsdPriceFeed.getRate();
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18
function frameEth() public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsd.mul(TENPOW18).div(_ethUsd);
}
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18 - including any bonuses
function frameEthBonus(address _address) public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsdWithBonus(_address).mul(TENPOW18).div(_ethUsd);
}
}
function calculateFrames(uint256 _ethAmount) public view returns (uint256 frames, uint256 ethToTransfer) {
return calculateEthFrames(_ethAmount, msg.sender);
}
function calculateUsdFrames(uint256 _usdAmount, address _tokenOwner) public view returns (uint256 frames, uint256 usdToTransfer) {
usdToTransfer = _usdAmount;
if (contributedUsd.add(usdToTransfer) > hardCapUsd) {
usdToTransfer = hardCapUsd.sub(contributedUsd);
}
// Get number of frames available to be purchased
frames = usdToTransfer.div(frameUsdWithBonus(_tokenOwner));
}
/// @notice Get frameEth rate including any bonuses
function calculateEthFrames(uint256 _ethAmount, address _tokenOwner) public view returns (uint256 frames, uint256 ethToTransfer) {
uint256 _frameEth;
uint256 _ethUsd;
bool _live;
(_ethUsd, _live) = ethUsd();
require(_live); // dev: Pricefeed not live
(_frameEth, _live) = frameEthBonus(_tokenOwner);
require(_live); // dev: Pricefeed not live
// USD able to be spent on available frames
uint256 usdAmount = _ethAmount.mul(_ethUsd).div(TENPOW18);
(frames, usdAmount) = calculateUsdFrames(usdAmount,_tokenOwner);
// Return ETH required for available frames
ethToTransfer = frames.mul(_frameEth);
}
// ----------------------------------------------------------------------------
// Crowd sale payments
// ----------------------------------------------------------------------------
/// @notice Buy FrameTokens by sending ETH to this contract address
receive() external payable {
buyFramesEth();
}
/// @notice Or calling this function and sending ETH
function buyFramesEth() public payable {
// Get number of frames remaining
uint256 ethToTransfer;
uint256 frames;
(frames, ethToTransfer) = calculateEthFrames( msg.value, msg.sender);
// Accept ETH Payments
uint256 ethToRefund = msg.value.sub(ethToTransfer);
if (ethToTransfer > 0) {
wallet.transfer(ethToTransfer);
}
// Return any ETH to be refundedf
if (ethToRefund > 0) {
msg.sender.transfer(ethToRefund);
}
// Claim FrameTokens
claimFrames(msg.sender,frames);
emit Purchased(msg.sender, frames, ethToTransfer, framesSold, contributedUsd);
}
/// @notice Operator allocates frames to tokenOwner for offchain purchases
function offlineFramesPurchase(address _tokenOwner, uint256 _frames) external {
// Only operator and owner can allocate frames offline
require(operators[msg.sender] || owner == msg.sender); // dev: Not operator
claimFrames(_tokenOwner,_frames);
emit Purchased(_tokenOwner, _frames, 0, framesSold, contributedUsd);
}
/// @notice Contract allocates frames to tokenOwner
function claimFrames(address _tokenOwner, uint256 _frames) internal {
require(!finalised, "Sale Finalised");
require(_frames > 0, "No frames available");
require(now >= startDate && now <= endDate, "Sale ended");
// Update crowdsale state
uint256 usdToTransfer = _frames.mul(frameUsdWithBonus(_tokenOwner));
require(contributedUsd.add(usdToTransfer) <= hardCapUsd, "Exceeds Hardcap");
contributedUsd = contributedUsd.add(usdToTransfer);
// Tokens locked and KYC check required if over AccountThresholdUsd
accountUsdAmount[_tokenOwner] = accountUsdAmount[_tokenOwner].add(usdToTransfer);
bool lockAccount = accountUsdAmount[_tokenOwner] > lockedAccountThresholdUsd;
// Mint FrameTokens
require(dreamFramesToken.mint(_tokenOwner, _frames.mul(TENPOW18), lockAccount)); // dev: Not Mintable
framesSold = framesSold.add(_frames);
if (contributedUsd >= hardCapUsd) {
finalised = true;
}
}
/// @notice Contract owner finalises crowdsale
function finalise(address _producer) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised || dreamFramesToken.mintable()); // dev: Already Finalised
require(now > endDate || contributedUsd >= hardCapUsd); // dev: Not Finished
finalised = true;
uint256 totalFrames = framesSold.mul(100).div(uint256(100).sub(producerPct));
uint256 producerFrames = totalFrames.sub(framesSold);
if (producerFrames > 0 && contributedUsd >= softCapUsd ) {
require(dreamFramesToken.mint(_producer, producerFrames.mul(TENPOW18), false)); // dev: Failed final mint
}
dreamFramesToken.disableMinting();
}
}
| @notice Operator allocates frames to tokenOwner for offchain purchases Only operator and owner can allocate frames offline | function offlineFramesPurchase(address _tokenOwner, uint256 _frames) external {
claimFrames(_tokenOwner,_frames);
emit Purchased(_tokenOwner, _frames, 0, framesSold, contributedUsd);
}
| 7,285,671 | [
1,
5592,
4767,
815,
7793,
358,
1147,
5541,
364,
3397,
5639,
5405,
343,
3304,
5098,
3726,
471,
3410,
848,
10101,
7793,
13493,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13493,
15162,
23164,
12,
2867,
389,
2316,
5541,
16,
2254,
5034,
389,
10278,
13,
3903,
225,
288,
203,
203,
3639,
7516,
15162,
24899,
2316,
5541,
16,
67,
10278,
1769,
203,
3639,
3626,
14466,
343,
8905,
24899,
2316,
5541,
16,
389,
10278,
16,
374,
16,
7793,
55,
1673,
16,
356,
11050,
3477,
72,
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
] |
./full_match/5/0x67dA37AbD98C317CE03bF428d3cA67d1d9128a07/sources/contracts/NokkoCollection.sol | uint256 public tokenCounter; | contract nokko is ERC721URIStorage, Ownable, ContractMetadata {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
pragma solidity ^0.8.0;
struct Transaction {
address sender;
address recipient;
uint amount;
uint timestamp;
}
Transaction[] public transactions;
struct NFTMetadata {
uint256 id;
string uri;
bool revealed;
}
mapping (uint256 => NFTMetadata) private _nftMetadata;
address public deployer;
constructor() ERC721("nokko", "NNFT") {
deployer = msg.sender;
}
struct BatchNFT {
uint256 id;
string uri;
bool isUnrevealed;
}
function mintNFTBatch(address to, BatchNFT[] memory nfts) public payable returns (BatchNFT[] memory) {
BatchNFT[] memory mintedNFTs = new BatchNFT[](nfts.length);
for (uint256 i = 0; i < nfts.length; i++) {
BatchNFT memory nft = nfts[i];
totalSupply++;
uint256 nftId = _tokenIds.current();
super._mint(to, nftId);
_setTokenURI(nftId, nft.uri);
_tokenIds.increment();
if (nft.isUnrevealed) {
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, false);
_nftMetadata[nftId] = metadata;
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, true);
_nftMetadata[nftId] = metadata;
}
mintedNFTs[i] = BatchNFT({
id: nft.id,
uri: nft.uri,
isUnrevealed: nft.isUnrevealed
});
}
address payable owner = payable(owner());
owner.transfer(msg.value);
return mintedNFTs;
}
function mintNFTBatch(address to, BatchNFT[] memory nfts) public payable returns (BatchNFT[] memory) {
BatchNFT[] memory mintedNFTs = new BatchNFT[](nfts.length);
for (uint256 i = 0; i < nfts.length; i++) {
BatchNFT memory nft = nfts[i];
totalSupply++;
uint256 nftId = _tokenIds.current();
super._mint(to, nftId);
_setTokenURI(nftId, nft.uri);
_tokenIds.increment();
if (nft.isUnrevealed) {
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, false);
_nftMetadata[nftId] = metadata;
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, true);
_nftMetadata[nftId] = metadata;
}
mintedNFTs[i] = BatchNFT({
id: nft.id,
uri: nft.uri,
isUnrevealed: nft.isUnrevealed
});
}
address payable owner = payable(owner());
owner.transfer(msg.value);
return mintedNFTs;
}
function mintNFTBatch(address to, BatchNFT[] memory nfts) public payable returns (BatchNFT[] memory) {
BatchNFT[] memory mintedNFTs = new BatchNFT[](nfts.length);
for (uint256 i = 0; i < nfts.length; i++) {
BatchNFT memory nft = nfts[i];
totalSupply++;
uint256 nftId = _tokenIds.current();
super._mint(to, nftId);
_setTokenURI(nftId, nft.uri);
_tokenIds.increment();
if (nft.isUnrevealed) {
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, false);
_nftMetadata[nftId] = metadata;
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, true);
_nftMetadata[nftId] = metadata;
}
mintedNFTs[i] = BatchNFT({
id: nft.id,
uri: nft.uri,
isUnrevealed: nft.isUnrevealed
});
}
address payable owner = payable(owner());
owner.transfer(msg.value);
return mintedNFTs;
}
} else {
function mintNFTBatch(address to, BatchNFT[] memory nfts) public payable returns (BatchNFT[] memory) {
BatchNFT[] memory mintedNFTs = new BatchNFT[](nfts.length);
for (uint256 i = 0; i < nfts.length; i++) {
BatchNFT memory nft = nfts[i];
totalSupply++;
uint256 nftId = _tokenIds.current();
super._mint(to, nftId);
_setTokenURI(nftId, nft.uri);
_tokenIds.increment();
if (nft.isUnrevealed) {
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, false);
_nftMetadata[nftId] = metadata;
NFTMetadata memory metadata = NFTMetadata(nft.id, nft.uri, true);
_nftMetadata[nftId] = metadata;
}
mintedNFTs[i] = BatchNFT({
id: nft.id,
uri: nft.uri,
isUnrevealed: nft.isUnrevealed
});
}
address payable owner = payable(owner());
owner.transfer(msg.value);
return mintedNFTs;
}
function revealBatchNFT(uint256[] memory tokenIds) public {
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
_nftMetadata[tokenId].revealed = true;
}
}
function revealBatchNFT(uint256[] memory tokenIds) public {
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
_nftMetadata[tokenId].revealed = true;
}
}
function isRevealed(uint256 tokenId) external view returns (bool) {
return _nftMetadata[tokenId].revealed;
}
function getNftId(uint256 tokenId) external view returns (uint256) {
return _nftMetadata[tokenId].id;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (_nftMetadata[tokenId].revealed) {
return super.tokenURI(tokenId);
return revealURl;
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (_nftMetadata[tokenId].revealed) {
return super.tokenURI(tokenId);
return revealURl;
}
}
} else {
function sendPayment() public payable {
require(msg.value > 0, "Invalid amount");
address payable owner = payable(owner());
owner.transfer(msg.value);
Transaction memory newTransaction = Transaction({
sender: msg.sender,
recipient: owner,
amount: msg.value,
timestamp: block.timestamp
});
transactions.push(newTransaction);
}
function sendPayment() public payable {
require(msg.value > 0, "Invalid amount");
address payable owner = payable(owner());
owner.transfer(msg.value);
Transaction memory newTransaction = Transaction({
sender: msg.sender,
recipient: owner,
amount: msg.value,
timestamp: block.timestamp
});
transactions.push(newTransaction);
}
function _canSetContractURI() internal view virtual override returns (bool){
return msg.sender == deployer;
}
}
| 1,922,889 | [
1,
11890,
5034,
1071,
1147,
4789,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
290,
601,
28179,
353,
4232,
39,
27,
5340,
3098,
3245,
16,
14223,
6914,
16,
13456,
2277,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
9354,
87,
18,
4789,
3238,
389,
2316,
2673,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
1958,
5947,
288,
203,
3639,
1758,
5793,
31,
203,
3639,
1758,
8027,
31,
203,
3639,
2254,
3844,
31,
203,
3639,
2254,
2858,
31,
203,
565,
289,
203,
203,
565,
5947,
8526,
1071,
8938,
31,
203,
203,
203,
203,
565,
1958,
423,
4464,
2277,
288,
203,
3639,
2254,
5034,
612,
31,
203,
3639,
533,
2003,
31,
203,
3639,
1426,
283,
537,
18931,
31,
203,
565,
289,
203,
203,
565,
2874,
261,
11890,
5034,
516,
423,
4464,
2277,
13,
3238,
389,
82,
1222,
2277,
31,
203,
565,
1758,
1071,
7286,
264,
31,
203,
203,
565,
3885,
1435,
4232,
39,
27,
5340,
2932,
82,
601,
28179,
3113,
315,
12225,
4464,
7923,
288,
203,
3639,
7286,
264,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
377,
1958,
5982,
50,
4464,
288,
203,
3639,
2254,
5034,
612,
31,
203,
3639,
533,
2003,
31,
203,
3639,
1426,
20488,
266,
537,
18931,
31,
203,
565,
289,
203,
203,
565,
445,
312,
474,
50,
4464,
4497,
12,
2867,
358,
16,
5982,
50,
4464,
8526,
3778,
290,
1222,
87,
13,
1071,
8843,
429,
1135,
261,
4497,
50,
4464,
8526,
3778,
13,
288,
203,
3639,
5982,
50,
4464,
2
] |
pragma solidity 0.4.25;
contract Election {
struct Elections
{
uint electionId;
string electionName;
uint candidateCount;
}
struct Candidate
{
uint candId;
uint electionId;
string candName;
uint voteCount;
}
struct VotedFace
{
string name;
uint electag;
uint count;
}
mapping(uint => Elections) public election;
mapping(uint => VotedFace) public votedface;
mapping(uint => Candidate) public candidate;
mapping(address => bool) public voters1;
mapping(address => bool) public voters2;
mapping(address => bool) public voters3;
mapping(address => bool) public voters4;
mapping(address => bool) public voters5;
mapping(address => bool) public voters6;
constructor () public {
addElections("General Secretary",3);
// addElections("Election Two",3);
addCandidate(1,"Arjun",0);
// addCandidate(2,"Adesh",0);
addCandidate(1,"Sulabh",0);
addCandidate(1,"Shubham",0);
// addCandidate(2,"Abhishek",0);
// addCandidate(2,"Bhavya",0);
}
uint public ElectionCount;
uint public CandidateCount;
uint public FaceCount;
event votedEvent (
uint indexed _candidateId
);
function addFace (string memory name,uint tag) public
{
FaceCount++;
votedface[FaceCount] = VotedFace(name,tag,FaceCount);
}
function addElections (string memory name,uint count) public
{
ElectionCount++;
election[ElectionCount] = Elections(ElectionCount,name,count);
}
function addCandidate (uint id,string memory name,uint vote) public
{
CandidateCount++;
candidate[CandidateCount]= Candidate(CandidateCount,id,name,vote);
}
function vote1 (uint _candidateId) public {
// require that they haven't voted before
require(!voters1[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= CandidateCount);
// record that voter has voted
voters1[msg.sender] = true;
// update candidate vote Count
candidate[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
function vote2 (uint _candidateId) public {
// require that they haven't voted before
require(!voters2[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= CandidateCount);
// record that voter has voted
voters2[msg.sender] = true;
// update candidate vote Count
candidate[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
function vote3 (uint _candidateId) public {
// require that they haven't voted before
require(!voters3[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= CandidateCount);
// record that voter has voted
voters3[msg.sender] = true;
// update candidate vote Count
candidate[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
function vote4 (uint _candidateId) public {
// require that they haven't voted before
require(!voters4[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= CandidateCount);
// record that voter has voted
voters4[msg.sender] = true;
// update candidate vote Count
candidate[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
function vote5 (uint _candidateId) public {
// require that they haven't voted before
require(!voters5[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= CandidateCount);
// record that voter has voted
voters5[msg.sender] = true;
// update candidate vote Count
candidate[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
function vote6 (uint _candidateId) public {
// require that they haven't voted before
require(!voters6[msg.sender]);
// require a valid candidate
require(_candidateId > 0 && _candidateId <= CandidateCount);
// record that voter has voted
voters6[msg.sender] = true;
// update candidate vote Count
candidate[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
} | require that they haven't voted before require a valid candidate record that voter has voted update candidate vote Count trigger voted event | function vote5 (uint _candidateId) public {
require(!voters5[msg.sender]);
require(_candidateId > 0 && _candidateId <= CandidateCount);
voters5[msg.sender] = true;
candidate[_candidateId].voteCount ++;
emit votedEvent(_candidateId);
}
| 7,289,186 | [
1,
6528,
716,
2898,
15032,
1404,
331,
16474,
1865,
2583,
279,
923,
5500,
1409,
716,
331,
20005,
711,
331,
16474,
1089,
5500,
12501,
6974,
3080,
331,
16474,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
445,
12501,
25,
261,
11890,
389,
19188,
548,
13,
1071,
288,
203,
540,
203,
3639,
2583,
12,
5,
90,
352,
414,
25,
63,
3576,
18,
15330,
19226,
203,
203,
3639,
2583,
24899,
19188,
548,
405,
374,
597,
389,
19188,
548,
1648,
385,
8824,
1380,
1769,
203,
203,
3639,
331,
352,
414,
25,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
203,
3639,
5500,
63,
67,
19188,
548,
8009,
25911,
1380,
965,
31,
203,
203,
3639,
3626,
331,
16474,
1133,
24899,
19188,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: Unlicense
pragma solidity 0.7.0;
import "./interfaces/IBank.sol";
import "./interfaces/IPriceOracle.sol";
import "./libraries/Math.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "hardhat/console.sol";
contract Bank is IBank {
using DSMath for uint256;
address private constant ethToken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address private hakToken; // = 0xBefeeD4CB8c6DD190793b1c97B72B60272f3EA6C;
mapping(address => Account) private ethDepAccountOf;
mapping(address => Account) private ethBorAccountOf;
mapping(address => Account) private hakDepAccountOf;
// mapping(address => Account) private hakBorAccountOf;
mapping(address => bool) private ethDepMutexOf;
mapping(address => bool) private ethBorMutexOf;
mapping(address => bool) private hakDepMutexOf;
// mapping(address => bool) private hakBorMutexOf;
IPriceOracle private priceOracle;
constructor(address _priceOracle, address _hakToken) {
priceOracle = IPriceOracle(_priceOracle);
hakToken = _hakToken;
console.log('constructor()');
console.log('constructor()', '_priceOracle:', _priceOracle);
console.log('constructor()', '_hakToken :', _hakToken);
console.log('');
}
/**
* The purpose of this function is to allow end-users to deposit a given
* token amount into their bank account.
* @param token - the address of the token to deposit. If this address is
* set to 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE then
* the token to deposit is ETH.
* @param amount - the amount of the given token to deposit.
* @return - true if the deposit was successful, otherwise revert.
*/
function deposit(address token, uint256 amount) payable external override returns (bool) {
console.log('deposit()');
console.log('deposit()', '_hakToken :', hakToken);
console.log('deposit()', 'token :', token);
console.log('deposit()', 'msg.sender:', msg.sender);
console.log('deposit()', 'amount :', amount);
console.log('deposit()', 'msg.value :', msg.value);
require(amount >= 0);
if (token == ethToken) {
console.log('deposit()', 'Case: ETH');
require(msg.value == amount);
require(!ethDepMutexOf[msg.sender]);
ethDepMutexOf[msg.sender] = true;
require(updateDepInterest(ethDepAccountOf[msg.sender]));
// TODO: How to RECEIVE ETH? .transfer doesn't work?
ethDepAccountOf[msg.sender].deposit = ethDepAccountOf[msg.sender].deposit.add(amount);
emit Deposit(msg.sender, token, amount);
ethDepMutexOf[msg.sender] = false;
console.log('');
return true;
} else if (token == hakToken) {
console.log('deposit()', 'Case: HAK');
require(!hakDepMutexOf[msg.sender]);
hakDepMutexOf[msg.sender] = true;
require(updateDepInterest(hakDepAccountOf[msg.sender]));
if (!IERC20(token).transferFrom(msg.sender, address(this), amount)) {
console.log('deposit()', 'Transaction failed!');
revert('transaction failed');
}
hakDepAccountOf[msg.sender].deposit = hakDepAccountOf[msg.sender].deposit.add(amount);
emit Deposit(msg.sender, token, amount);
hakDepMutexOf[msg.sender] = false;
console.log('');
return true;
} else {
console.log('deposit()', 'Case: Not supported');
console.log('');
revert('token not supported');
}
}
/**
* The purpose of this function is to allow end-users to withdraw a given
* token amount from their bank account. Upon withdrawal, the user must
* automatically receive a 3% interest rate per 100 blocks on their deposit.
* @param token - the address of the token to withdraw. If this address is
* set to 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE then
* the token to withdraw is ETH.
* @param amount - the amount of the given token to withdraw. If this param
* is set to 0, then the maximum amount available in the
* caller's account should be withdrawn.
* @return - the amount that was withdrawn plus interest upon success,
* otherwise revert.
*/
function withdraw(address token, uint256 amount) external override returns (uint256) {
console.log('withdraw()');
console.log('withdraw()', '_hakToken :', hakToken);
console.log('withdraw()', 'token :', token);
console.log('withdraw()', 'msg.sender:', msg.sender);
console.log('withdraw()', 'amount :', amount);
require(amount >= 0);
if (token == ethToken) {
console.log('withdraw()', 'Case: ETH');
// require(msg.value == amount);
// TypeError: "msg.value" and "callvalue()" can only be used in payable public functions.
// Make the function "payable" or use an internal function to avoid this error.
require(!ethDepMutexOf[msg.sender]);
ethDepMutexOf[msg.sender] = true;
require(updateDepInterest(ethDepAccountOf[msg.sender]));
if (ethDepAccountOf[msg.sender].deposit.add(ethDepAccountOf[msg.sender].interest) == 0) {
revert('no balance');
}
if (amount > ethDepAccountOf[msg.sender].deposit.add(ethDepAccountOf[msg.sender].interest)) {
revert('amount exceeds balance');
}
// Withdraw all:
if (amount == 0) {
amount = ethDepAccountOf[msg.sender].deposit.add(ethDepAccountOf[msg.sender].interest);
}
if (amount <= ethDepAccountOf[msg.sender].interest) {
ethDepAccountOf[msg.sender].interest = ethDepAccountOf[msg.sender].interest.sub(amount);
} else {
ethDepAccountOf[msg.sender].deposit = ethDepAccountOf[msg.sender].deposit.sub(amount - ethDepAccountOf[msg.sender].interest);
ethDepAccountOf[msg.sender].interest = 0;
}
msg.sender.transfer(amount); // .transfer() of ETH.
emit Withdraw(msg.sender, token, amount);
ethDepMutexOf[msg.sender] = false;
console.log('');
return amount;
} else if (token == hakToken) {
console.log('withdraw()', 'Case: HAK');
require(!hakDepMutexOf[msg.sender]);
hakDepMutexOf[msg.sender] = true;
require(updateDepInterest(hakDepAccountOf[msg.sender]));
if (hakDepAccountOf[msg.sender].deposit.add(hakDepAccountOf[msg.sender].interest) == 0) {
revert('no balance');
}
if (amount > hakDepAccountOf[msg.sender].deposit.add(hakDepAccountOf[msg.sender].interest)) {
revert('amount exceeds balance');
}
// Withdraw all:
if (amount == 0) {
amount = hakDepAccountOf[msg.sender].deposit.add(hakDepAccountOf[msg.sender].interest);
}
if (amount <= hakDepAccountOf[msg.sender].interest) {
hakDepAccountOf[msg.sender].interest = hakDepAccountOf[msg.sender].interest.sub(amount);
} else {
hakDepAccountOf[msg.sender].deposit = hakDepAccountOf[msg.sender].deposit.sub(amount - hakDepAccountOf[msg.sender].interest);
hakDepAccountOf[msg.sender].interest = 0;
}
IERC20(token).transferFrom(address(this), msg.sender, amount); // .transfer() of ERC20.
emit Withdraw(msg.sender, token, amount);
hakDepMutexOf[msg.sender] = false;
console.log('');
return amount;
} else {
console.log('withdraw()', 'Case: Not supported');
console.log('');
revert('token not supported');
}
}
/**
* The purpose of this function is to allow users to borrow funds by using their
* deposited funds as collateral. The minimum ratio of deposited funds over
* borrowed funds must not be less than 150%.
* @param token - the address of the token to borrow. This address must be
* set to 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, otherwise
* the transaction must revert.
* @param amount - the amount to borrow. If this amount is set to zero (0),
* then the amount borrowed should be the maximum allowed,
* while respecting the collateral ratio of 150%.
* @return - the current collateral ratio.
*/
function borrow(address token, uint256 amount) external override returns (uint256) {
console.log('borrow()');
console.log('borrow()', '_hakToken :', hakToken);
console.log('borrow()', 'token :', token);
console.log('borrow()', 'msg.sender:', msg.sender);
console.log('borrow()', 'amount :', amount);
if (token != ethToken) {
revert('token not supported');
}
require(amount >= 0);
require((!ethBorMutexOf[msg.sender]) && (!hakDepMutexOf[msg.sender]));
ethBorMutexOf[msg.sender] = true;
hakDepMutexOf[msg.sender] = true;
if (hakDepAccountOf[msg.sender].deposit == 0) {
revert('no collateral deposited');
}
require(updateDepInterest(hakDepAccountOf[msg.sender]));
require(updateBorInterest(ethBorAccountOf[msg.sender]));
uint256 HAKinETH = priceOracle.getVirtualPrice(hakToken); //address of HAK
console.log('borrow()', 'HAKinETH :', HAKinETH);
uint256 ethBalance = ethBorAccountOf[msg.sender].deposit.add(ethBorAccountOf[msg.sender].interest);
uint256 hakBalance = hakDepAccountOf[msg.sender].deposit.add(hakDepAccountOf[msg.sender].interest);
uint256 hakBalanceinETH = hakBalance.mul(HAKinETH) / (1 ether);
console.log('borrow()', 'ethBalance:', ethBalance);
console.log('borrow()', 'hakBalance:', hakBalance);
console.log('borrow()', 'hakBalETH :', hakBalanceinETH);
// Collateral ratio = (Deposited funds in HAK) / (Borrowed funds in ETH):
uint256 cur_ratio;
uint256 new_ratio;
uint256 end_ratio;
if (ethBalance == 0) {
cur_ratio = type(uint256).max;
if (amount > 0) {
new_ratio = hakBalanceinETH.mul(10000) / ethBalance.add(amount);
} else if (amount == 0) { // Maximum borrow.
new_ratio = uint256(15000); // Irrelevant.
}
} else {
cur_ratio = hakBalanceinETH.mul(10000) / ethBalance;
new_ratio = hakBalanceinETH.mul(10000) / ethBalance.add(amount);
}
console.log('borrow()', 'cur_ratio :', cur_ratio);
console.log('borrow()', 'new_ratio :', new_ratio);
if (new_ratio >= uint256(15000)) {
if (amount == 0) {
console.log('borrow()', 'Case: Max loan.');
end_ratio = uint256(15000);
uint256 amount_max = (hakBalanceinETH.mul(10000) / end_ratio).sub(ethBalance);
console.log('borrow()', 'amount_max:', amount_max);
ethBorAccountOf[msg.sender].deposit = ethBorAccountOf[msg.sender].deposit.add(amount_max);
msg.sender.transfer(amount_max); // .transfer() of ETH.
emit Borrow(msg.sender, token, amount_max, end_ratio);
} else if (amount > 0) {
console.log('borrow()', 'Case: Loan approved.');
end_ratio = new_ratio;
ethBorAccountOf[msg.sender].deposit = ethBorAccountOf[msg.sender].deposit.add(amount);
msg.sender.transfer(amount); // .transfer() of ETH.
emit Borrow(msg.sender, token, amount, end_ratio);
}
ethBorMutexOf[msg.sender] = false;
hakDepMutexOf[msg.sender] = false;
console.log('borrow()', 'end_ratio :', end_ratio);
console.log('');
} else {
console.log('borrow()', 'Case: Loan rejected.');
end_ratio = cur_ratio;
ethBorMutexOf[msg.sender] = false;
hakDepMutexOf[msg.sender] = false;
console.log('borrow()', 'end_ratio :', end_ratio);
console.log('');
revert('borrow would exceed collateral ratio');
}
return end_ratio;
}
/**
* The purpose of this function is to allow users to repay their loans.
* Loans can be repaid partially or entirely. When replaying a loan, an
* interest payment is also required. The interest on a loan is equal to
* 5% of the amount lent per 100 blocks. If the loan is repaid earlier,
* or later then the interest should be proportional to the number of
* blocks that the amount was borrowed for.
* @param token - the address of the token to repay. If this address is
* set to 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE then
* the token is ETH.
* @param amount - the amount to repay including the interest.
* @return - the amount still left to pay for this loan, excluding interest.
*/
function repay(address token, uint256 amount) payable external override returns (uint256) {
console.log('repay()');
console.log('repay()', '_hakToken :', hakToken);
console.log('repay()', 'token :', token);
console.log('repay()', 'msg.sender:', msg.sender);
console.log('repay()', 'amount :', amount);
if (token != ethToken) {
revert('token not supported');
}
require(amount >= 0);
require(!ethBorMutexOf[msg.sender]);
ethBorMutexOf[msg.sender] = true;
require(updateBorInterest(ethBorAccountOf[msg.sender]));
console.log('repay()', 'deposit :', ethBorAccountOf[msg.sender].deposit);
console.log('repay()', 'interest :', ethBorAccountOf[msg.sender].interest);
if (ethBorAccountOf[msg.sender].deposit.add(ethBorAccountOf[msg.sender].interest) == 0) {
revert('nothing to repay');
}
if (msg.value < amount) { // msg.value wouldn't be zero because we are handling ETH.
revert('msg.value < amount to repay');
}
require(amount <= ethBorAccountOf[msg.sender].deposit.add(ethBorAccountOf[msg.sender].interest), '');
if (amount == 0) {
amount = ethBorAccountOf[msg.sender].deposit.add(ethBorAccountOf[msg.sender].interest);
}
// TODO: How to RECEIVE ETH? .transfer doesn't work?
if (amount <= ethBorAccountOf[msg.sender].interest) {
ethBorAccountOf[msg.sender].interest = ethBorAccountOf[msg.sender].interest.sub(amount);
} else {
ethBorAccountOf[msg.sender].deposit = ethBorAccountOf[msg.sender].deposit.sub(amount.sub(ethBorAccountOf[msg.sender].interest));
ethBorAccountOf[msg.sender].interest = 0;
}
console.log('repay()', 'deposit :', ethBorAccountOf[msg.sender].deposit);
console.log('repay()', 'interest :', ethBorAccountOf[msg.sender].interest);
emit Repay(msg.sender, token, ethBorAccountOf[msg.sender].deposit.add(ethBorAccountOf[msg.sender].interest));
ethBorMutexOf[msg.sender] = false;
console.log('');
return ethBorAccountOf[msg.sender].deposit;
}
/**
* The purpose of this function is to allow so called keepers to collect bad
* debt, that is in case the collateral ratio goes below 150% for any loan.
* @param token - the address of the token used as collateral for the loan.
* @param account - the account that took out the loan that is now undercollateralized.
* @return - true if the liquidation was successful, otherwise revert.
*/
function liquidate(address token, address account) payable external override returns (bool) {
console.log('liquidate()');
console.log('liquidate()', '_hakToken :', hakToken);
console.log('liquidate()', 'token :', token);
console.log('liquidate()', 'msg.sender:', msg.sender);
console.log('liquidate()', 'account :', account);
if (token != hakToken) {
revert('token not supported');
}
if (account == msg.sender) {
revert('cannot liquidate own position');
}
require(!ethBorMutexOf[account] && !hakDepMutexOf[account]);
ethBorMutexOf[account] = true;
hakDepMutexOf[account] = true;
require(updateBorInterest(ethBorAccountOf[account]));
require(updateDepInterest(hakDepAccountOf[account]));
uint256 collateral_ratio = this.getCollateralRatio(token, account);
console.log('liquidate()', 'coll_ratio:', collateral_ratio);
if (collateral_ratio >= 15000) {
ethBorMutexOf[account] = false;
hakDepMutexOf[account] = false;
revert('healty position');
}
require(!ethDepMutexOf[msg.sender] && !hakDepMutexOf[msg.sender]);
ethDepMutexOf[msg.sender] = true;
hakDepMutexOf[msg.sender] = true;
require(updateDepInterest(ethDepAccountOf[msg.sender]));
require(updateDepInterest(hakDepAccountOf[msg.sender]));
// Collateral ratio < 150%.
// if (ethDepAccountOf[msg.sender].deposit.add(ethDepAccountOf[msg.sender].interest) >= ethBorAccountOf[account].deposit.add(ethBorAccountOf[account].interest)) {
if (msg.value >= ethBorAccountOf[account].deposit.add(ethBorAccountOf[account].interest)) {
console.log('liquidate()', 'Liquidator has sufficient ETH to liquidate account.');
// uint256 excessETH = ethDepAccountOf[msg.sender].deposit.add(ethDepAccountOf[msg.sender].interest) - ethBorAccountOf[account].deposit.add(ethBorAccountOf[account].interest);
uint256 excessETH = msg.value - ethBorAccountOf[account].deposit.add(ethBorAccountOf[account].interest);
uint256 collateral = hakDepAccountOf[account].deposit.add(hakDepAccountOf[account].interest);
console.log('liquidate()', 'excessETH :', excessETH);
console.log('liquidate()', 'collateral:', collateral);
hakDepAccountOf[msg.sender].deposit = hakDepAccountOf[msg.sender].deposit.add(collateral);
hakDepAccountOf[account].deposit = 0;
hakDepAccountOf[account].interest = 0;
ethBorAccountOf[account].deposit = 0;
ethBorAccountOf[account].interest = 0;
emit Liquidate(msg.sender, account, token, collateral, excessETH);
ethBorMutexOf[account] = false;
hakDepMutexOf[account] = false;
ethDepMutexOf[msg.sender] = false;
hakDepMutexOf[msg.sender] = false;
console.log('');
return true;
} else {
console.log('liquidate()', 'Liquidation failed. Liquidator has insufficient ETH funds.');
ethBorMutexOf[account] = false;
hakDepMutexOf[account] = false;
ethDepMutexOf[msg.sender] = false;
hakDepMutexOf[msg.sender] = false;
console.log('');
revert('insufficient ETH sent by liquidator');
}
}
/**
* The purpose of this function is to return the collateral ratio for any account.
* The collateral ratio is computed as the value deposited divided by the value
* borrowed. However, if no value is borrowed then the function should return
* uint256 MAX_INT = type(uint256).max
* @param token - the address of the deposited token used a collateral for the loan.
* @param account - the account that took out the loan.
* @return - the value of the collateral ratio with 2 percentage decimals, e.g. 1% = 100.
* If the account has no deposits for the given token then return zero (0).
* If the account has deposited token, but has not borrowed anything then
* return MAX_INT.
*/
function getCollateralRatio(address token, address account) view external override returns (uint256) {
console.log('getCollateralRatio()');
console.log('getCollateralRatio()', '_hakToken :', hakToken);
console.log('getCollateralRatio()', 'token :', token);
console.log('getCollateralRatio()', 'msg.sender:', msg.sender);
console.log('getCollateralRatio()', 'account :', account);
if (hakDepAccountOf[account].deposit == 0) {
// revert('no collateral deposited');
return 0;
} else if (ethBorAccountOf[account].deposit.add(checkBorInterest(ethBorAccountOf[account])) == 0) {
return type(uint256).max;
}
uint256 HAKinETH = priceOracle.getVirtualPrice(hakToken); //address of HAK
console.log('getCollateralRatio()', 'HAKinETH :', HAKinETH);
uint256 ethBalance = ethBorAccountOf[account].deposit.add(checkBorInterest(ethBorAccountOf[account]));
uint256 hakBalance = hakDepAccountOf[account].deposit.add(checkDepInterest(hakDepAccountOf[account]));
uint256 hakBalanceinETH = hakBalance.mul(HAKinETH) / (1 ether);
console.log('getCollateralRatio()', 'ethBalance:', ethBalance);
console.log('getCollateralRatio()', 'hakBalance:', hakBalance);
console.log('getCollateralRatio()', 'hakBalETH :', hakBalanceinETH);
// Collateral ratio = (Deposited funds in HAK) / (Borrowed funds in ETH):
uint256 cur_ratio = hakBalanceinETH.mul(10000) / ethBalance;
console.log('getCollateralRatio()', 'cur_ratio :', cur_ratio);
console.log('');
return cur_ratio;
}
/**
* The purpose of this function is to return the balance that the caller
* has in their own account for the given token (including interest).
* @param token - the address of the token for which the balance is computed.
* @return - the value of the caller's balance with interest, excluding debts.
*/
function getBalance(address token) view external override returns (uint256) {
if (token == ethToken){
return ethDepAccountOf[msg.sender].deposit.add(checkDepInterest(ethDepAccountOf[msg.sender]));
} else if (token == hakToken) {
return hakDepAccountOf[msg.sender].deposit.add(checkDepInterest(hakDepAccountOf[msg.sender]));
} else {
revert('token not supported');
}
}
/**
* Update account interest to current block, for deposit/withdraw.
* @param account_ - user Account. Can be either eth or hak.
* @return - true if success.
*/
function updateDepInterest(Account storage account_) private returns (bool) {
require(block.number - account_.lastInterestBlock > 0);
account_.interest += account_.deposit * 3 / 100 * (block.number - account_.lastInterestBlock) / 100;
account_.lastInterestBlock = block.number;
return true;
}
/**
* Update account interest to current block, for borrow/repay.
* @param account_ - user Account. Can be either eth or hak.
* @return - true if success.
*/
function updateBorInterest(Account storage account_) private returns (bool) {
require(block.number - account_.lastInterestBlock >= 0);
account_.interest += account_.deposit * 5 / 100 * (block.number - account_.lastInterestBlock) / 100;
account_.lastInterestBlock = block.number;
return true;
}
/**
* Compute account interest without update, for checking account balance.
* @param account_ - user Account. Can be either eth or hak.
* @return - current accrued interest.
*/
function checkDepInterest(Account storage account_) view private returns (uint256) {
require(block.number - account_.lastInterestBlock >= 0);
uint256 interest = account_.interest + account_.deposit * 3 / 100 * (block.number - account_.lastInterestBlock) / 100;
return interest;
}
/**
* Compute borrow interest without update, for checking account balance.
* @param account_ - user Account. Can be either eth or hak.
* @return - current accrued interest.
*/
function checkBorInterest(Account storage account_) view private returns (uint256) {
require(block.number - account_.lastInterestBlock >= 0);
uint256 interest = account_.interest + account_.deposit * 5 / 100 * (block.number - account_.lastInterestBlock) / 100;
return interest;
}
}
| Collateral ratio = (Deposited funds in HAK) / (Borrowed funds in ETH): | uint256 cur_ratio = hakBalanceinETH.mul(10000) / ethBalance;
| 7,294,380 | [
1,
13535,
2045,
287,
7169,
273,
261,
758,
1724,
329,
284,
19156,
316,
670,
14607,
13,
342,
261,
38,
15318,
329,
284,
19156,
316,
512,
2455,
4672,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
2254,
5034,
662,
67,
9847,
273,
366,
581,
13937,
267,
1584,
44,
18,
16411,
12,
23899,
13,
342,
13750,
13937,
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
] |
//SPDX-License-Identifier: Unlicensed
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
//ANTIS INU (THE SHIBA KILLER)
//https://antisinu.com
/*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%%##*********##%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#*+=============-------=+*#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@%#*++++*##%@@@@@@@@@@@@@@@@%#**+===+#%@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@#*++*#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#*+++*#@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@#*=+*#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#*++*%@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@*==+#@@@@@@@@%%@@@@@@@@@@@@@@@@@@@@@@@@@%%@@@@@@@#*++#@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@*==+%@@@@@@@@%####%%@@@@@@@@@@@@@@@@@@@%%%###%@@@@@@@%*==*@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@*--+%@@@@@@@@@@##*+**%%%@@@@@@@@@@@@@@@%%%#*+*##@@@@@@@@@%+==*@@@@@@@@@@@@@@
@@@@@@@@@@@@%=-=#@@@@@@@@@@@@#+==+=+#%%@@@@@@@@@@@@@@%#+=++=+*%@@@@@@@@@@%=-=#@@@@@@@@@@@@
@@@@@@@@@@@*--+@@@@@@@@@@@@@#+===+==*%%@@@@@@@@@@@@@%%*==+====*@@@@@@@@@@@@*--+@@@@@@@@@@@
@@@@@@@@@@=:-#@@@@@@@@@@@@@@#++===+=+%%@@@@@@@@@@@@@%%+=++==++*@@@@@@@@@@@@@%--=@@@@@@@@@@
@@@@@@@@@-:-%@@@@@@@@@@@@@@#*++++=+==#%%@@@@@@@@@@@%%#==+==++++#@@@@@@@@@@@@@%=:-@@@@@@@@@
@@@@@@@@=:-%@@@@@@@@@@@@@@@+=++=++=++%%%@@@@@@@@@@@%%%+++++=++=+%@@@@@@@@@@@@@@-:-@@@@@@@@
@@@@@@@+::%@@@@@@@@@@@@@@@#++=+==+++*%%%%@@@@@@@@@%%%%*+++==+=++*@@@@@@@@@@@@@@%-:=@@@@@@@
@@@@@@#::*@@@@@@@@@@@@@@@@*=++++===+########%%%########+===++++=+@@@@@@@@@@@@@@@*::#@@@@@@
@@@@@@-:-@@@@@@@@@@@@@@@@@+++=+++=+******++*****++******+=+++=+++@@@@@@@@@@@@@@@@-::@@@@@@
@@@@@#.:*@@@@@@@@@@@@@@@@@*+=++++****++====+***+====++****++++++*@@@@@@@@@@@@@@@@#:.*@@@@@
@@@@@=.:@@@@@@@@@@@@@@@@@@#*++=+*#*++=======+*+========+*#*+==+*#@@@@@@@@@@@@@@@@@:.-@@@@@
@@@@@:.-@@@@@@@@@@@@@@@@@@%***+*#*+==========*==========+*#*+***#@@@@@@@@@@@@@@@@@=..@@@@@
@@@@@..+@@@@@@@@@@@@@@@@@@%######+=====+====+*+====+=====+######%@@@@@@@@@@@@@@@@@+..%@@@@
@@@@%..+@@@@@@@@@@@@@@@@@@%#%%%#+===+*%%%===***+==#%%#+===+#%%%##@@@@@@@@@@@@@@@@@*..%@@@@
@@@@@..+@@@@@@@@@@@@@@@@@@@%###*===#***@%*=*****=+%%#**#+==+####@@@@@@@@@@@@@@@@@@+..%@@@@
@@@@@:.-@@@@@@@@@@@@@@@@@@@@%##====*######*******###%##*====##%@@@@@@@@@@@@@@@@@@@=..@@@@@
@@@@@=.:@@@@@@@@@@@@@@@@@@@@@#*========+****###****++=======*#@@@@@@@@@@@@@@@@@@@@:.-@@@@@
@@@@@#.:*@@@@@@@@@@@@@@@@@@@%#**++======***#####***======++**#%@@@@@@@@@@@@@@@@@@#:.*@@@@@
@@@@@@-:-@@@@@@@@@@@@@@@@@@%#****+=====+*#########*+=====+****#%@@@@@@@@@@@@@@@@@-::@@@@@@
@@@@@@#::*@@@@@@@@@@@@@@@@%****+******+#############*+*****+**#*#@@@@@@@@@@@@@@@*::*@@@@@@
@@@@@@@+::%@@@@@@@@@@@@@@@%@@#++******###**+===++*###******++#@@%@@@@@@@@@@@@@@%-:=@@@@@@@
@@@@@@@@-:-%@@@@@@@@@@@@@@@@@#+*******####%%%#%%%####*******+#@@@@@@@@@@@@@@@@@-:-@@@@@@@@
@@@@@@@@@-:-%@@@@@@@@@@@@@@@@#+*#*+***####%@@@@@%#####**+*#**#@@@@@@@@@@@@@@@@=:-@@@@@@@@@
@@@@@@@@@@=:-#@@@@@@@@@@@@@@@%#@@*+**#######%%%#######**+*%@%#@@@@@@@@@@@@@@%--=@@@@@@@@@@
@@@@@@@@@@@+--*@@@@@@@@@@@@@@@@@@****######%%%%%######****@@@@@@@@@@@@@@@@@*--+@@@@@@@@@@@
@@@@@@@@@@@@#--=%@@@@@@@@@@@@@@@@%@#***#############***#@%@@@@@@@@@@@@@@@%+-=#@@@@@@@@@@@@
@@@@@@@@@@@@@@*--+%@@@@@@@@@@@@@@@@@#***++*+++++**+***#@@@@@@@@@@@@@@@@%*==*@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@*==+%@@@@@@@@@@@@@@@@#%*****++++**+*%#@@@@@@@@@@@@@@@%*==*@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@*==+#@@@@@@@@@@@@@@@@@%@%#+++*%@#@@@@@@@@@@@@@@@@%*++*@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@#+=+*#@@@@@@@@@@@@@@@@@@%+#@@@@@@@@@@@@@@@@@#*++*#@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@#*++*#%@@@@@@@@@@@@@@@#@@@@@@@@@@@@@@%*+++*#@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@%#*+++**#%%@@@@@@@@@@@@@@@@%##*+===+*%@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#**+==============------=+*#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%##****++++**##%%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/3_Ballot.sol
pragma solidity ^0.8.10;
contract AntisInuToken is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
uint256 public swapTokensAtAmount = 2 * 10**7 * (10**9);
uint256 public maxWalletLimit = 15 * 10**8 * 10**9; // 3% of the supply
uint256 public maxTxAmount = 25 * 10**7 * 10**9; // 0.5% of the supply
uint8 public marketingFee = 10;
uint16 internal totalFees = marketingFee;
address public bridge;
address payable public _marketingWallet = payable(address(0x456)); // MARKETING WALLET
mapping (address => bool) public _isBlacklisted;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
constructor(address _bridge) ERC20("ANTIS INU", "ANTIS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
bridge = _bridge;
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(_bridge, true);
excludeFromFees(address(this), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(_bridge, 30 * 10**9 * (10**9)); // 30,000,000,000 Tokens
}
receive() external payable {}
function decimals() public pure override returns(uint8) {
return 9;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "COOL: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), uniswapV2Router.WETH());
uniswapV2Pair = _uniswapV2Pair;
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
require(_isExcludedFromFees[account] != excluded, "COOL: Account is already excluded");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
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 setMarketingWallet(address payable wallet) external onlyOwner{
_marketingWallet = wallet;
}
function addToBlackList (address [] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++ i) {
_isBlacklisted [addresses [i]] = true;}
}
function setSwapAtAmount(uint256 value) external onlyOwner {
swapTokensAtAmount = value;
}
function setMaxWalletAmount(uint256 value) external onlyOwner {
maxWalletLimit = value;
}
function setMaxTxAmount(uint256 value) external onlyOwner {
maxTxAmount = value;
}
function setmarketingFee(uint8 value) external onlyOwner{
marketingFee = value;
totalFees = marketingFee;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "COOL: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
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), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require (! _isBlacklisted [from] &&! _isBlacklisted [to], "This address is blacklisted");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if( canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != owner() &&
to != owner()
) {
swapping = true;
contractTokenBalance = swapTokensAtAmount;
swapAndSendToFee(contractTokenBalance);
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
require(amount <= maxTxAmount,"Transfer amount exceeds limit");
if(!automatedMarketMakerPairs[to]){
require(amount + balanceOf(to) <= maxWalletLimit,"Wallet limit reached");
}
uint256 fees = amount.mul(totalFees).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
}
function claimStuckTokens(address _token) external onlyOwner {
if (_token == address(0x0)) {
payable(owner()).transfer(address(this).balance);
return;
}
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.transfer(owner(), balance);
}
function swapAndSendToFee(uint256 tokens) private {
uint256 initialBalance = address(this).balance;
swapTokensForBNB(tokens);
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 forMarketing = newBalance;
_marketingWallet.transfer(forMarketing);
}
function swapTokensForBNB(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
);
}
} | Create a uniswap pair for this new token exclude from paying fees or having max transaction amount | constructor(address _bridge) ERC20("ANTIS INU", "ANTIS") {
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
bridge = _bridge;
excludeFromFees(owner(), true);
excludeFromFees(_bridge, true);
excludeFromFees(address(this), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
| 1,110,227 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
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
] | [
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,
3885,
12,
2867,
389,
18337,
13,
4232,
39,
3462,
2932,
6856,
5127,
2120,
57,
3113,
315,
6856,
5127,
7923,
288,
203,
203,
3639,
1758,
389,
318,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
389,
318,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
24899,
318,
291,
91,
438,
58,
22,
4154,
16,
638,
1769,
203,
3639,
10105,
273,
389,
18337,
31,
203,
203,
3639,
4433,
1265,
2954,
281,
12,
8443,
9334,
638,
1769,
203,
3639,
4433,
1265,
2954,
281,
24899,
18337,
16,
638,
1769,
203,
3639,
4433,
1265,
2954,
281,
12,
2867,
12,
2211,
3631,
638,
1769,
203,
203,
5411,
389,
81,
474,
353,
392,
2713,
445,
316,
4232,
39,
3462,
18,
18281,
716,
353,
1338,
2566,
2674,
16,
203,
5411,
471,
385,
16791,
506,
2566,
14103,
3382,
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
] |
./full_match/1/0xDF19e2f273363D86DfE5A2ed44422ada32eFaa62/sources/contract.sol | it('name, symbol, decimals, totalSupply, balanceOf, DOMAIN_SEPARATOR, PERMIT_TYPEHASH', async () => { const name = await token.name() expect(name).to.eq('Uniswap V2') expect(await token.symbol()).to.eq('UNI-V2') expect(await token.decimals()).to.eq(18) expect(await token.totalSupply()).to.eq(TOTAL_SUPPLY) expect(await token.balanceOf(wallet.address)).to.eq(TOTAL_SUPPLY) expect(await token.DOMAIN_SEPARATOR()).to.eq( keccak256( | contract Manager {
function performTasks() public {
}
function uniswapDepositAddress() public pure returns (address) {
return 0xcc3e0035B0cb3aC8D7D0C6E08bCC8BA4f316B1E8;
}
}
| 8,429,941 | [
1,
305,
2668,
529,
16,
3273,
16,
15105,
16,
2078,
3088,
1283,
16,
11013,
951,
16,
27025,
67,
4550,
16,
10950,
6068,
67,
2399,
15920,
2187,
4326,
1832,
516,
288,
377,
1866,
508,
273,
4273,
1147,
18,
529,
1435,
377,
4489,
12,
529,
2934,
869,
18,
11253,
2668,
984,
291,
91,
438,
776,
22,
6134,
377,
4489,
12,
30515,
1147,
18,
7175,
1435,
2934,
869,
18,
11253,
2668,
10377,
17,
58,
22,
6134,
377,
4489,
12,
30515,
1147,
18,
31734,
1435,
2934,
869,
18,
11253,
12,
2643,
13,
377,
4489,
12,
30515,
1147,
18,
4963,
3088,
1283,
1435,
2934,
869,
18,
11253,
12,
28624,
67,
13272,
23893,
13,
377,
4489,
12,
30515,
1147,
18,
12296,
951,
12,
19177,
18,
2867,
13,
2934,
869,
18,
11253,
12,
28624,
67,
13272,
23893,
13,
377,
4489,
12,
30515,
1147,
18,
18192,
67,
4550,
1435,
2934,
869,
18,
11253,
12,
4202,
417,
24410,
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,
8558,
288,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
282,
445,
3073,
6685,
1435,
1071,
288,
203,
202,
377,
203,
282,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
282,
445,
640,
291,
91,
438,
758,
1724,
1887,
1435,
1071,
16618,
1135,
261,
2867,
13,
288,
203,
202,
2463,
374,
92,
952,
23,
73,
713,
4763,
38,
20,
7358,
23,
69,
39,
28,
40,
27,
40,
20,
39,
26,
41,
6840,
70,
6743,
28,
12536,
24,
74,
23,
2313,
38,
21,
41,
28,
31,
203,
282,
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
] |
pragma solidity ^0.4.18;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint256 public totalSupply;
string public name;
string public symbol;
uint8 public decimals;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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 Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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;
}
}
contract HybridBlock is ERC20 {
using SafeMath for uint256;
// The owner of this token
address public owner;
// The balance in HybridBlock token that every address has
mapping (address => uint256) balances;
// Keeps track of allowances for particular address
mapping (address => mapping (address => uint256)) public allowed;
/**
* The constructor for the HybridBlock token
*/
function HybridBlock() public {
owner = 0x35118ba64fD141F43958cF9EB493F13aca976e6a;
name = "Hybrid Block";
symbol = "HYB";
decimals = 18;
totalSupply = 1e9 * 10 ** uint256(decimals);
// Initially allocate all minted tokens to the owner
balances[owner] = totalSupply;
}
/**
* @dev Retrieves the balance of a specified address
* @param _owner address The address to query the balance of.
* @return A uint256 representing the amount owned by the _owner
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfers tokens to a specific address
* @param _to address The address to transfer tokens to
* @param _value unit256 The amount to be transferred
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// Subtract first
balances[msg.sender] = balances[msg.sender].sub(_value);
// Now add tokens
balances[_to] = balances[_to].add(_value);
// Notify that a transfer has occurred
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer on behalf of another address
* @param _from address The address to send tokens from
* @param _to address The address to send tokens 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]);
// Decrease both the _from amount and the allowed transfer amount
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
// Give _to the tokens
balances[_to] = balances[_to].add(_value);
// Notify that a transfer has occurred
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve sent address to spend the specified amount of tokens on
* behalf of msg.sender
*
* See https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* for any potential security concerns
*
* @param _spender address The address that will spend funds
* @param _value uint256 The number of tokens they are allowed to spend
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Returns the amount a spender is allowed to spend for a particular
* address
* @param _owner address The address which owns the funds
* @param _spender address The address which will spend the funds.
* @return uint256 The number of tokens still available for the spender
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increases the number of tokens a spender is allowed to spend for
* `msg.sender`
* @param _spender address The address of the spender
* @param _addedValue uint256 The amount to increase the spenders approval by
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decreases the number of tokens a spender is allowed to spend for
* `msg.sender`
* @param _spender address The address of the spender
* @param _subtractedValue uint256 The amount to decrease the spenders approval by
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint _value = allowed[msg.sender][_spender];
if (_subtractedValue > _value) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = _value.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | * @dev Decreases the number of tokens a spender is allowed to spend for `msg.sender` @param _spender address The address of the spender @param _subtractedValue uint256 The amount to decrease the spenders approval by/ | function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint _value = allowed[msg.sender][_spender];
if (_subtractedValue > _value) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = _value.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 2,213,255 | [
1,
23326,
3304,
326,
1300,
434,
2430,
279,
17571,
264,
353,
2935,
358,
17571,
364,
1375,
3576,
18,
15330,
68,
225,
389,
87,
1302,
264,
1758,
1021,
1758,
434,
326,
17571,
264,
225,
389,
1717,
1575,
329,
620,
2254,
5034,
1021,
3844,
358,
20467,
326,
17571,
414,
23556,
635,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
20467,
23461,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1717,
1575,
329,
620,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2254,
389,
1132,
273,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
15533,
203,
565,
309,
261,
67,
1717,
1575,
329,
620,
405,
389,
1132,
13,
288,
203,
1377,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
374,
31,
203,
1377,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
18,
1717,
24899,
1717,
1575,
329,
620,
1769,
203,
565,
289,
203,
203,
565,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
19226,
203,
565,
327,
638,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/LibBit.sol | @dev Returns `x & y`. Inputs must be clean. | function rawAnd(bool x, bool y) internal pure returns (bool z) {
assembly {
z := and(x, y)
}
}
| 4,875,536 | [
1,
1356,
1375,
92,
473,
677,
8338,
24472,
1297,
506,
2721,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1831,
1876,
12,
6430,
619,
16,
1426,
677,
13,
2713,
16618,
1135,
261,
6430,
998,
13,
288,
203,
203,
203,
3639,
19931,
288,
203,
5411,
998,
519,
471,
12,
92,
16,
677,
13,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xd571788859897023b500c6c7fd295bba1e7ff71c
//Contract name: SportStarMaster
//Balance: 0.003422924159669719 Ether
//Verification Date: 3/9/2018
//Transacion Count: 4
// CODE STARTS HERE
pragma solidity ^0.4.18; // solhint-disable-line
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract SportStarToken is ERC721 {
// ***** EVENTS
// @dev Transfer event as defined in current draft of ERC721.
// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
// ***** STORAGE
// @dev A mapping from token IDs to the address that owns them. All tokens have
// some valid owner address.
mapping (uint256 => address) public tokenIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
// @dev A mapping from TokenIDs to an address that has been approved to call
// transferFrom(). Each Token can only have one approved address for transfer
// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public tokenIndexToApproved;
// Additional token data
mapping (uint256 => bytes32) public tokenIndexToData;
address public ceoAddress;
address public masterContractAddress;
uint256 public promoCreatedCount;
// ***** DATATYPES
struct Token {
string name;
}
Token[] private tokens;
// ***** ACCESS MODIFIERS
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyMasterContract() {
require(msg.sender == masterContractAddress);
_;
}
// ***** CONSTRUCTOR
function SportStarToken() public {
ceoAddress = msg.sender;
}
// ***** PRIVILEGES SETTING FUNCTIONS
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setMasterContract(address _newMasterContract) public onlyCEO {
require(_newMasterContract != address(0));
masterContractAddress = _newMasterContract;
}
// ***** PUBLIC FUNCTIONS
// @notice Returns all the relevant information about a specific token.
// @param _tokenId The tokenId of the token of interest.
function getToken(uint256 _tokenId) public view returns (
string tokenName,
address owner
) {
Token storage token = tokens[_tokenId];
tokenName = token.name;
owner = tokenIndexToOwner[_tokenId];
}
// @param _owner The owner whose sport star tokens we are interested in.
// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
// expensive (it walks the entire Tokens array looking for tokens belonging to owner),
// but it also returns a dynamic array, which is only supported for web3 calls, and
// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTokens = totalSupply();
uint256 resultIndex = 0;
uint256 tokenId;
for (tokenId = 0; tokenId <= totalTokens; tokenId++) {
if (tokenIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
function getTokenData(uint256 _tokenId) public view returns (bytes32 tokenData) {
return tokenIndexToData[_tokenId];
}
// ***** ERC-721 FUNCTIONS
// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
// @param _to The address to be granted transfer approval. Pass address(0) to
// clear all approvals.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function approve(address _to, uint256 _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
tokenIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
// For querying balance of a particular account
// @param _owner The address for balance query
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function name() public pure returns (string) {
return "CryptoSportStars";
}
function symbol() public pure returns (string) {
return "SportStarToken";
}
function implementsERC721() public pure returns (bool) {
return true;
}
// For querying owner of token
// @param _tokenId The tokenID for owner inquiry
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
owner = tokenIndexToOwner[_tokenId];
require(owner != address(0));
}
// @notice Allow pre-approved user to take ownership of a token
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = tokenIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
// For querying totalSupply of token
function totalSupply() public view returns (uint256 total) {
return tokens.length;
}
// Owner initates the transfer of the token to another account
// @param _to The address for the token to be transferred to.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function transfer(address _to, uint256 _tokenId) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
// Third-party initiates transfer of token from address _from to address _to
// @param _from The address for the token to be transferred from.
// @param _to The address for the token to be transferred to.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function transferFrom(address _from, address _to, uint256 _tokenId) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
// ONLY MASTER CONTRACT FUNCTIONS
function createToken(string _name, address _owner) public onlyMasterContract returns (uint256 _tokenId) {
return _createToken(_name, _owner);
}
function updateOwner(address _from, address _to, uint256 _tokenId) public onlyMasterContract {
_transfer(_from, _to, _tokenId);
}
function setTokenData(uint256 _tokenId, bytes32 tokenData) public onlyMasterContract {
tokenIndexToData[_tokenId] = tokenData;
}
// PRIVATE FUNCTIONS
// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return tokenIndexToApproved[_tokenId] == _to;
}
// For creating Token
function _createToken(string _name, address _owner) private returns (uint256 _tokenId) {
Token memory _token = Token({
name: _name
});
uint256 newTokenId = tokens.push(_token) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newTokenId == uint256(uint32(newTokenId)));
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newTokenId);
return newTokenId;
}
// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == tokenIndexToOwner[_tokenId];
}
// @dev Assigns ownership of a specific Token to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of tokens is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
tokenIndexToOwner[_tokenId] = _to;
// When creating new tokens _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete tokenIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
}
contract SportStarMaster {
// ***** EVENTS ***/
// @dev The Birth event is fired whenever a new token comes into existence.
event Birth(uint256 tokenId, string name, address owner);
// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner);
// @dev Transfer event as defined in current draft of ERC721.
// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
// ***** CONSTANTS ***/
uint256 private startingPrice = 0.001 ether;
uint256 private firstStepLimit = 0.053613 ether;
uint256 private secondStepLimit = 0.564957 ether;
// ***** STORAGE ***/
// @dev A mapping from TokenIDs to the price of the token.
mapping(uint256 => uint256) private tokenIndexToPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cooAddress;
// The address of tokens contract
SportStarToken public tokensContract;
uint256 public promoCreatedCount;
uint256 private increaseLimit1 = 0.05 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 2.0 ether;
uint256 private increaseLimit4 = 5.0 ether;
// ***** ACCESS MODIFIERS ***/
// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
// Access modifier for contract owner only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
// ***** CONSTRUCTOR ***/
function SportStarMaster() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
//Old prices
tokenIndexToPrice[0]=198056585936481135;
tokenIndexToPrice[1]=198056585936481135;
tokenIndexToPrice[2]=198056585936481135;
tokenIndexToPrice[3]=76833314470700771;
tokenIndexToPrice[4]=76833314470700771;
tokenIndexToPrice[5]=76833314470700771;
tokenIndexToPrice[6]=76833314470700771;
tokenIndexToPrice[7]=76833314470700771;
tokenIndexToPrice[8]=76833314470700771;
tokenIndexToPrice[9]=76833314470700771;
tokenIndexToPrice[10]=76833314470700771;
tokenIndexToPrice[11]=76833314470700771;
tokenIndexToPrice[12]=76833314470700771;
tokenIndexToPrice[13]=76833314470700771;
tokenIndexToPrice[14]=37264157518289874;
tokenIndexToPrice[15]=76833314470700771;
tokenIndexToPrice[16]=144447284479990001;
tokenIndexToPrice[17]=144447284479990001;
tokenIndexToPrice[18]=37264157518289874;
tokenIndexToPrice[19]=76833314470700771;
tokenIndexToPrice[20]=37264157518289874;
tokenIndexToPrice[21]=76833314470700771;
tokenIndexToPrice[22]=105348771387661881;
tokenIndexToPrice[23]=144447284479990001;
tokenIndexToPrice[24]=105348771387661881;
tokenIndexToPrice[25]=37264157518289874;
tokenIndexToPrice[26]=37264157518289874;
tokenIndexToPrice[27]=37264157518289874;
tokenIndexToPrice[28]=76833314470700771;
tokenIndexToPrice[29]=105348771387661881;
tokenIndexToPrice[30]=76833314470700771;
tokenIndexToPrice[31]=37264157518289874;
tokenIndexToPrice[32]=76833314470700771;
tokenIndexToPrice[33]=37264157518289874;
tokenIndexToPrice[34]=76833314470700771;
tokenIndexToPrice[35]=37264157518289874;
tokenIndexToPrice[36]=37264157518289874;
tokenIndexToPrice[37]=76833314470700771;
tokenIndexToPrice[38]=76833314470700771;
tokenIndexToPrice[39]=37264157518289874;
tokenIndexToPrice[40]=37264157518289874;
tokenIndexToPrice[41]=37264157518289874;
tokenIndexToPrice[42]=76833314470700771;
tokenIndexToPrice[43]=37264157518289874;
tokenIndexToPrice[44]=37264157518289874;
tokenIndexToPrice[45]=76833314470700771;
tokenIndexToPrice[46]=37264157518289874;
tokenIndexToPrice[47]=37264157518289874;
tokenIndexToPrice[48]=76833314470700771;
}
function setTokensContract(address _newTokensContract) public onlyCEO {
require(_newTokensContract != address(0));
tokensContract = SportStarToken(_newTokensContract);
}
// ***** PRIVILEGES SETTING FUNCTIONS
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
// ***** PUBLIC FUNCTIONS ***/
function getTokenInfo(uint256 _tokenId) public view returns (
address owner,
uint256 price,
bytes32 tokenData
) {
owner = tokensContract.ownerOf(_tokenId);
price = tokenIndexToPrice[_tokenId];
tokenData = tokensContract.getTokenData(_tokenId);
}
// @dev Creates a new promo Token with the given name, with given _price and assignes it to an address.
function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO {
address tokenOwner = _owner;
if (tokenOwner == address(0)) {
tokenOwner = cooAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
uint256 newTokenId = tokensContract.createToken(_name, tokenOwner);
tokenIndexToPrice[newTokenId] = _price;
Birth(newTokenId, _name, _owner);
}
// @dev Creates a new Token with the given name.
function createContractToken(string _name) public onlyCOO {
uint256 newTokenId = tokensContract.createToken(_name, address(this));
tokenIndexToPrice[newTokenId] = startingPrice;
Birth(newTokenId, _name, address(this));
}
function createContractTokenWithPrice(string _name, uint256 _price) public onlyCOO {
uint256 newTokenId = tokensContract.createToken(_name, address(this));
tokenIndexToPrice[newTokenId] = _price;
Birth(newTokenId, _name, address(this));
}
function setGamblingFee(uint256 _tokenId, uint256 _fee) public {
require(msg.sender == tokensContract.ownerOf(_tokenId));
require(_fee >= 0 && _fee <= 100);
bytes32 tokenData = byte(_fee);
tokensContract.setTokenData(_tokenId, tokenData);
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable {
address oldOwner = tokensContract.ownerOf(_tokenId);
address newOwner = msg.sender;
uint256 sellingPrice = tokenIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 devCut = calculateDevCut(sellingPrice);
uint256 payment = SafeMath.sub(sellingPrice, devCut);
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
tokenIndexToPrice[_tokenId] = calculateNextPrice(sellingPrice);
tokensContract.updateOwner(oldOwner, newOwner, _tokenId);
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment);
}
TokenSold(_tokenId, sellingPrice, tokenIndexToPrice[_tokenId], oldOwner, newOwner);
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return tokenIndexToPrice[_tokenId];
}
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3%
} else if (_price < increaseLimit2) {
return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3%
} else if (_price < increaseLimit3) {
return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3%
} else if (_price < increaseLimit4) {
return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3%
} else {
return SafeMath.div(SafeMath.mul(_price, 2), 100); // 2%
}
}
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return SafeMath.div(SafeMath.mul(_price, 200), 97);
} else if (_price < increaseLimit2) {
return SafeMath.div(SafeMath.mul(_price, 133), 97);
} else if (_price < increaseLimit3) {
return SafeMath.div(SafeMath.mul(_price, 125), 97);
} else if (_price < increaseLimit4) {
return SafeMath.div(SafeMath.mul(_price, 115), 97);
} else {
return SafeMath.div(SafeMath.mul(_price, 113), 98);
}
}
function payout(address _to) public onlyCEO {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
// PRIVATE FUNCTIONS
// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| @notice Returns all the relevant information about a specific token. @param _tokenId The tokenId of the token of interest. | function getToken(uint256 _tokenId) public view returns (
string tokenName,
address owner
) {
Token storage token = tokens[_tokenId];
tokenName = token.name;
owner = tokenIndexToOwner[_tokenId];
}
| 1,008,795 | [
1,
1356,
777,
326,
9368,
1779,
2973,
279,
2923,
1147,
18,
225,
389,
2316,
548,
1021,
1147,
548,
434,
326,
1147,
434,
16513,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9162,
12,
11890,
5034,
389,
2316,
548,
13,
1071,
1476,
1135,
261,
203,
3639,
533,
1147,
461,
16,
203,
3639,
1758,
3410,
203,
565,
262,
288,
203,
3639,
3155,
2502,
1147,
273,
2430,
63,
67,
2316,
548,
15533,
203,
3639,
1147,
461,
273,
1147,
18,
529,
31,
203,
3639,
3410,
273,
1147,
1016,
774,
5541,
63,
67,
2316,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.7;
// Batch transfer Ether and Wesion
/**
* @title SafeMath for uint256
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath256 {
/**
* @dev Multiplies two unsigned integers, reverts 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;
}
}
/**
* @title Ownable
*/
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;
}
/**
* @return The address of the owner.
*/
function owner() public view returns (address) {
return _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @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) external onlyOwner {
require(newOwner != address(0));
address __previousOwner = _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_owner = newOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit OwnershipTransferred(__previousOwner, newOwner);
}
/**
* @dev Rescue compatible ERC20 Token
*
* @param tokenAddr ERC20 The address of the ERC20 token contract
* @param receiver The address of the receiver
* @param amount uint256
*/
function rescueTokens(address tokenAddr, address receiver, uint256 amount) external onlyOwner {
IERC20 __token = IERC20(tokenAddr);
require(receiver != address(0));
uint256 __balance = __token.balanceOf(address(this));
require(__balance >= amount);
assert(__token.transfer(receiver, amount));
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20{
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
}
/**
* @title Batch Transfer Ether And Wesion
*/
contract BatchTransferEtherAndWesion is Ownable{
using SafeMath256 for uint256;
IERC20 Wesion = IERC20(0x2c1564A74F07757765642ACef62a583B38d5A213);
/**
* @dev Batch transfer both.
*/
function batchTransfer(address payable[] memory accounts, uint256 etherValue, uint256 vokenValue) public payable {
uint256 __etherBalance = address(this).balance;
uint256 __vokenAllowance = Wesion.allowance(msg.sender, address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(__etherBalance >= etherValue.mul(accounts.length));
require(__vokenAllowance >= vokenValue.mul(accounts.length));
for (uint256 i = 0; i < accounts.length; i++) {
accounts[i].transfer(etherValue);
assert(Wesion.transferFrom(msg.sender, accounts[i], vokenValue)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
/**
* @dev Batch transfer Ether.
*/
function batchTtransferEther(address payable[] memory accounts, uint256 etherValue) public payable {
uint256 __etherBalance = address(this).balance;
require(__etherBalance >= etherValue.mul(accounts.length));
for (uint256 i = 0; i < accounts.length; i++) {
accounts[i].transfer(etherValue);
}
}
/**
* @dev Batch transfer Wesion.
*/
function batchTransferWesion(address[] memory accounts, uint256 wesionValue) public {
uint256 _wesionAllowance = Wesion.allowance(msg.sender, address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(_wesionAllowance >= wesionValue.mul(accounts.length));
for (uint256 i = 0; i < accounts.length; i++) {
assert(Wesion.transferFrom(msg.sender, accounts[i], wesionValue)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
/**
* @dev set Wesion Address
*/
function setWesionAddress(address _WesionAddr) public onlyOwner {
Wesion = IERC20(_WesionAddr); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
} | inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
| assert(Wesion.transferFrom(msg.sender, accounts[i], wesionValue)); | 1,004,694 | [
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
1815,
12,
59,
281,
285,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
9484,
63,
77,
6487,
341,
281,
285,
620,
10019,
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
] |
./partial_match/3/0xf03518534Ec76AEb697C99cFE0CDA08077091c7B/sources/Heroes.sol | * @dev Gets the owner of the specified token ID @param tokenID uint256 ID of the token to query the owner of @return 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;
}
| 5,226,180 | [
1,
3002,
326,
3410,
434,
326,
1269,
1147,
1599,
225,
1147,
734,
2254,
5034,
1599,
434,
326,
1147,
358,
843,
326,
3410,
434,
327,
1758,
4551,
9350,
487,
326,
3410,
434,
326,
864,
1147,
1599,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3410,
951,
12,
11890,
5034,
1147,
734,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
1758,
3410,
273,
389,
2316,
5541,
63,
2316,
734,
15533,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
10019,
203,
3639,
327,
3410,
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
] |
//Address: 0x77e01450fd870dafa3a545bdfc2b6e13c879f645
//Contract name: TokenVesting
//Balance: -
//Verification Date: 1/31/2018
//Transacion Count: 0
// CODE STARTS HERE
//File: node_modules/zeppelin-solidity/contracts/token/ERC20Basic.sol
pragma solidity ^0.4.18;
/**
* @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);
}
//File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/BasicToken.sol
pragma solidity ^0.4.18;
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
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);
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];
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20.sol
pragma solidity ^0.4.18;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//File: node_modules/zeppelin-solidity/contracts/token/StandardToken.sol
pragma solidity ^0.4.18;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
//File: node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/MintableToken.sol
pragma solidity ^0.4.18;
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
//File: node_modules/zeppelin-solidity/contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.4.18;
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// 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(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
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) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/SafeERC20.sol
pragma solidity ^0.4.18;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
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));
}
}
//File: node_modules/zeppelin-solidity/contracts/token/TokenVesting.sol
pragma solidity ^0.4.18;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
//File: node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.18;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
//File: node_modules/zeppelin-solidity/contracts/token/PausableToken.sol
pragma solidity ^0.4.18;
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
//File: src/contracts/ico/MtnToken.sol
/**
* @title MTN token
*
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.18;
contract MtnToken is MintableToken, PausableToken {
string public constant name = "MedToken";
string public constant symbol = "MTN";
uint8 public constant decimals = 18;
/**
* @dev Constructor of MtnToken that instantiates a new Mintable Pauseable Token
*/
function MtnToken() public {
// token should not be transferrable until after all tokens have been issued
paused = true;
}
}
//File: src/contracts/ico/MtnCrowdsale.sol
/**
* @title MtnCrowdsale
*
* Simple time and TOKEN_CAPped based crowdsale.
*
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.18;
contract MtnCrowdsale is Ownable, Crowdsale {
/*** CONSTANTS ***/
uint256 public constant TOTAL_TOKEN_CAP = 500e6 * 1e18; // 500 million * 1e18 - smallest unit of MTN token
uint256 public constant CROWDSALE_TOKENS = 175e6 * 1e18; // 175 million * 1e18 - presale and crowdsale tokens
uint256 public constant TOTAL_TEAM_TOKENS = 170e6 * 1e18; // 170 million * 1e18 - team tokens
uint256 public constant TEAM_TOKENS0 = 50e6 * 1e18; // 50 million * 1e18 - team tokens, already vested
uint256 public constant TEAM_TOKENS1 = 60e6 * 1e18; // 60 million * 1e18 - team tokens, vesting over 2 years
uint256 public constant TEAM_TOKENS2 = 60e6 * 1e18; // 60 million * 1e18 - team tokens, vesting over 4 years
uint256 public constant COMMUNITY_TOKENS = 155e6 * 1e18; // 155 million * 1e18 - community tokens, vesting over 4 years
uint256 public constant MAX_CONTRIBUTION_USD = 5000; // USD
uint256 public constant USD_CENT_PER_TOKEN = 25; // in cents - smallest unit of USD E.g. 100 = 1 USD
uint256 public constant VESTING_DURATION_4Y = 4 years;
uint256 public constant VESTING_DURATION_2Y = 2 years;
// true if address is allowed to invest
mapping(address => bool) public isWhitelisted;
// allow managers to whitelist and confirm contributions by manager accounts
// managers can be set and altered by owner, multiple manager accounts are possible
mapping(address => bool) public isManager;
uint256 public maxContributionInWei;
uint256 public tokensMinted; // already minted tokens (maximally = TOKEN_CAP)
bool public capReached; // set to true when cap has been reached when minting tokens
mapping(address => uint256) public totalInvestedPerAddress;
address public beneficiaryWallet;
// for convenience we store vesting wallets
address public teamVesting2Years;
address public teamVesting4Years;
address public communityVesting4Years;
/*** Tracking Crowdsale Stages ***/
bool public isCrowdsaleOver;
/*** EVENTS ***/
event ChangedManager(address manager, bool active);
event PresaleMinted(address indexed beneficiary, uint256 tokenAmount);
event ChangedInvestorWhitelisting(address indexed investor, bool whitelisted);
/*** MODIFIERS ***/
modifier onlyManager() {
require(isManager[msg.sender]);
_;
}
// trying to accompish using already existing variables to determine stage - prevents manual updating of the enum stage states
modifier onlyPresalePhase() {
require(now < startTime);
_;
}
modifier onlyCrowdsalePhase() {
require(now >= startTime && now < endTime && !isCrowdsaleOver);
_;
}
modifier respectCrowdsaleCap(uint256 _amount) {
require(tokensMinted.add(_amount) <= CROWDSALE_TOKENS);
_;
}
modifier onlyCrowdSaleOver() {
require(isCrowdsaleOver || now > endTime || capReached);
_;
}
modifier onlyValidAddress(address _address) {
require(_address != address(0));
_;
}
/**
* @dev Deploy MTN Token Crowdsale
* @param _startTime uint256 Start time of the crowdsale
* @param _endTime uint256 End time of the crowdsale
* @param _usdPerEth uint256 issueing rate tokens per wei
* @param _wallet address Wallet address of the crowdsale
* @param _beneficiaryWallet address wallet holding team and community tokens
*/
function MtnCrowdsale(
uint256 _startTime,
uint256 _endTime,
uint256 _usdPerEth,
address _wallet,
address _beneficiaryWallet
)
Crowdsale(_startTime, _endTime, (_usdPerEth.mul(1e2)).div(USD_CENT_PER_TOKEN), _wallet)
public
onlyValidAddress(_beneficiaryWallet)
{
require(TOTAL_TOKEN_CAP == CROWDSALE_TOKENS.add(TOTAL_TEAM_TOKENS).add(COMMUNITY_TOKENS));
require(TOTAL_TEAM_TOKENS == TEAM_TOKENS0.add(TEAM_TOKENS1).add(TEAM_TOKENS2));
setManager(msg.sender, true);
beneficiaryWallet = _beneficiaryWallet;
maxContributionInWei = (MAX_CONTRIBUTION_USD.mul(1e18)).div(_usdPerEth);
mintTeamTokens();
mintCommunityTokens();
}
/**
* @dev Create new instance of mtn token contract
*/
function createTokenContract() internal returns (MintableToken) {
return new MtnToken();
}
/**
* @dev Set / alter manager / whitelister "account". This can be done from owner only
* @param _manager address address of the manager to create/alter
* @param _active bool flag that shows if the manager account is active
*/
function setManager(address _manager, bool _active) public onlyOwner onlyValidAddress(_manager) {
isManager[_manager] = _active;
ChangedManager(_manager, _active);
}
/**
* @dev whitelist investors to allow the direct investment of this crowdsale
* @param _investor address address of the investor to be whitelisted
*/
function whiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
isWhitelisted[_investor] = true;
ChangedInvestorWhitelisting(_investor, true);
}
/**
* @dev whitelist several investors via a batch method
* @param _investors address[] array of addresses of the beneficiaries to receive tokens after they have been confirmed
*/
function batchWhiteListInvestors(address[] _investors) public onlyManager {
for (uint256 c; c < _investors.length; c = c.add(1)) {
whiteListInvestor(_investors[c]);
}
}
/**
* @dev unwhitelist investor from participating in the crowdsale
* @param _investor address address of the investor to disallowed participation
*/
function unWhiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
isWhitelisted[_investor] = false;
ChangedInvestorWhitelisting(_investor, false);
}
/**
* @dev onlyOwner allowed to mint tokens, respecting the cap, and only before the crowdsale starts
* @param _beneficiary address
* @param _amount uint256
*/
function mintTokenPreSale(address _beneficiary, uint256 _amount) public onlyOwner onlyPresalePhase onlyValidAddress(_beneficiary) respectCrowdsaleCap(_amount) {
require(_amount > 0);
tokensMinted = tokensMinted.add(_amount);
token.mint(_beneficiary, _amount);
PresaleMinted(_beneficiary, _amount);
}
/**
* @dev onlyOwner allowed to handle batch presale minting
* @param _beneficiaries address[]
* @param _amounts uint256[]
*/
function batchMintTokenPresale(address[] _beneficiaries, uint256[] _amounts) public onlyOwner onlyPresalePhase {
require(_beneficiaries.length == _amounts.length);
for (uint256 i; i < _beneficiaries.length; i = i.add(1)) {
mintTokenPreSale(_beneficiaries[i], _amounts[i]);
}
}
/**
* @dev override core functionality by whitelist check
* @param _beneficiary address
*/
function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
require(isWhitelisted[msg.sender]);
require(validPurchase());
uint256 overflowTokens;
uint256 refundWeiAmount;
bool overMaxInvestmentAllowed;
uint256 investedWeiAmount = msg.value;
// Is this specific investment over the MAX_CONTRIBUTION_USD limit?
// if so, calcuate wei refunded and tokens to mint for the allowed investment amount
uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
if (totalInvestedWeiAmount > maxContributionInWei) {
overMaxInvestmentAllowed = true;
refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
uint256 tokenAmount = investedWeiAmount.mul(rate);
uint256 tempMintedTokens = tokensMinted.add(tokenAmount); // gas optimization, do not inline twice
// check to see if this purchase sets it over the crowdsale token cap
// if so, calculate tokens to mint, then refund the remaining ether investment
if (tempMintedTokens >= CROWDSALE_TOKENS) {
capReached = true;
overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
tokenAmount = tokenAmount.sub(overflowTokens);
refundWeiAmount = overflowTokens.div(rate);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
weiRaised = weiRaised.add(investedWeiAmount);
tokensMinted = tokensMinted.add(tokenAmount);
TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
token.mint(_beneficiary, tokenAmount);
// if investor breached cap and has remaining ether not invested
// refund remaining ether to investor
if (capReached || overMaxInvestmentAllowed) {
msg.sender.transfer(refundWeiAmount);
wallet.transfer(investedWeiAmount);
} else {
forwardFunds();
}
}
/**
* @dev onlyOwner to close Crowdsale manually if before endTime
*/
function closeCrowdsale() public onlyOwner onlyCrowdsalePhase {
isCrowdsaleOver = true;
}
/**
* @dev onlyOwner allows tokens to be tradeable
*/
function finalize() public onlyOwner onlyCrowdSaleOver {
// do not allow new owner to mint further tokens & unpause token to allow trading
MintableToken(token).finishMinting();
PausableToken(token).unpause();
}
/*** INTERNAL/PRIVATE FUNCTIONS ***/
/**
* @dev allows contract owner to mint all team tokens per TEAM_TOKENS and have 50m immediately available, 60m 2 years vested, and 60m over 4 years vesting
*/
function mintTeamTokens() private {
token.mint(beneficiaryWallet, TEAM_TOKENS0);
TokenVesting newVault1 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_2Y, false);
teamVesting2Years = address(newVault1); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
token.mint(address(newVault1), TEAM_TOKENS1);
TokenVesting newVault2 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
teamVesting4Years = address(newVault2); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
token.mint(address(newVault2), TEAM_TOKENS2);
}
/**
* @dev allows contract owner to mint all community tokens per COMMUNITY_TOKENS and have the vested to the beneficiaryWallet
*/
function mintCommunityTokens() private {
TokenVesting newVault = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
communityVesting4Years = address(newVault); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
token.mint(address(newVault), COMMUNITY_TOKENS);
}
/**
* @dev extend base functionality with min investment amount
*/
function validPurchase() internal view respectCrowdsaleCap(0) returns (bool) {
require(!capReached);
require(totalInvestedPerAddress[msg.sender] < maxContributionInWei);
return super.validPurchase();
}
}
| true if address is allowed to invest allow managers to whitelist and confirm contributions by manager accounts managers can be set and altered by owner, multiple manager accounts are possible for convenience we store vesting wallets | contract MtnCrowdsale is Ownable, Crowdsale {
uint256 public constant VESTING_DURATION_4Y = 4 years;
uint256 public constant VESTING_DURATION_2Y = 2 years;
mapping(address => bool) public isWhitelisted;
mapping(address => bool) public isManager;
uint256 public maxContributionInWei;
mapping(address => uint256) public totalInvestedPerAddress;
address public beneficiaryWallet;
address public teamVesting2Years;
address public teamVesting4Years;
address public communityVesting4Years;
bool public isCrowdsaleOver;
event ChangedManager(address manager, bool active);
event PresaleMinted(address indexed beneficiary, uint256 tokenAmount);
event ChangedInvestorWhitelisting(address indexed investor, bool whitelisted);
pragma solidity ^0.4.18;
modifier onlyManager() {
require(isManager[msg.sender]);
_;
}
modifier onlyPresalePhase() {
require(now < startTime);
_;
}
modifier onlyCrowdsalePhase() {
require(now >= startTime && now < endTime && !isCrowdsaleOver);
_;
}
modifier respectCrowdsaleCap(uint256 _amount) {
require(tokensMinted.add(_amount) <= CROWDSALE_TOKENS);
_;
}
modifier onlyCrowdSaleOver() {
require(isCrowdsaleOver || now > endTime || capReached);
_;
}
modifier onlyValidAddress(address _address) {
require(_address != address(0));
_;
}
function MtnCrowdsale(
uint256 _startTime,
uint256 _endTime,
uint256 _usdPerEth,
address _wallet,
address _beneficiaryWallet
)
Crowdsale(_startTime, _endTime, (_usdPerEth.mul(1e2)).div(USD_CENT_PER_TOKEN), _wallet)
public
onlyValidAddress(_beneficiaryWallet)
{
require(TOTAL_TOKEN_CAP == CROWDSALE_TOKENS.add(TOTAL_TEAM_TOKENS).add(COMMUNITY_TOKENS));
require(TOTAL_TEAM_TOKENS == TEAM_TOKENS0.add(TEAM_TOKENS1).add(TEAM_TOKENS2));
setManager(msg.sender, true);
beneficiaryWallet = _beneficiaryWallet;
maxContributionInWei = (MAX_CONTRIBUTION_USD.mul(1e18)).div(_usdPerEth);
mintTeamTokens();
mintCommunityTokens();
}
function createTokenContract() internal returns (MintableToken) {
return new MtnToken();
}
function setManager(address _manager, bool _active) public onlyOwner onlyValidAddress(_manager) {
isManager[_manager] = _active;
ChangedManager(_manager, _active);
}
function whiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
isWhitelisted[_investor] = true;
ChangedInvestorWhitelisting(_investor, true);
}
function batchWhiteListInvestors(address[] _investors) public onlyManager {
for (uint256 c; c < _investors.length; c = c.add(1)) {
whiteListInvestor(_investors[c]);
}
}
function batchWhiteListInvestors(address[] _investors) public onlyManager {
for (uint256 c; c < _investors.length; c = c.add(1)) {
whiteListInvestor(_investors[c]);
}
}
function unWhiteListInvestor(address _investor) public onlyManager onlyValidAddress(_investor) {
isWhitelisted[_investor] = false;
ChangedInvestorWhitelisting(_investor, false);
}
function mintTokenPreSale(address _beneficiary, uint256 _amount) public onlyOwner onlyPresalePhase onlyValidAddress(_beneficiary) respectCrowdsaleCap(_amount) {
require(_amount > 0);
tokensMinted = tokensMinted.add(_amount);
token.mint(_beneficiary, _amount);
PresaleMinted(_beneficiary, _amount);
}
function batchMintTokenPresale(address[] _beneficiaries, uint256[] _amounts) public onlyOwner onlyPresalePhase {
require(_beneficiaries.length == _amounts.length);
for (uint256 i; i < _beneficiaries.length; i = i.add(1)) {
mintTokenPreSale(_beneficiaries[i], _amounts[i]);
}
}
function batchMintTokenPresale(address[] _beneficiaries, uint256[] _amounts) public onlyOwner onlyPresalePhase {
require(_beneficiaries.length == _amounts.length);
for (uint256 i; i < _beneficiaries.length; i = i.add(1)) {
mintTokenPreSale(_beneficiaries[i], _amounts[i]);
}
}
function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
require(isWhitelisted[msg.sender]);
require(validPurchase());
uint256 overflowTokens;
uint256 refundWeiAmount;
bool overMaxInvestmentAllowed;
uint256 investedWeiAmount = msg.value;
uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
if (totalInvestedWeiAmount > maxContributionInWei) {
overMaxInvestmentAllowed = true;
refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
uint256 tokenAmount = investedWeiAmount.mul(rate);
if (tempMintedTokens >= CROWDSALE_TOKENS) {
capReached = true;
overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
tokenAmount = tokenAmount.sub(overflowTokens);
refundWeiAmount = overflowTokens.div(rate);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
weiRaised = weiRaised.add(investedWeiAmount);
tokensMinted = tokensMinted.add(tokenAmount);
TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
token.mint(_beneficiary, tokenAmount);
if (capReached || overMaxInvestmentAllowed) {
msg.sender.transfer(refundWeiAmount);
wallet.transfer(investedWeiAmount);
forwardFunds();
}
}
function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
require(isWhitelisted[msg.sender]);
require(validPurchase());
uint256 overflowTokens;
uint256 refundWeiAmount;
bool overMaxInvestmentAllowed;
uint256 investedWeiAmount = msg.value;
uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
if (totalInvestedWeiAmount > maxContributionInWei) {
overMaxInvestmentAllowed = true;
refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
uint256 tokenAmount = investedWeiAmount.mul(rate);
if (tempMintedTokens >= CROWDSALE_TOKENS) {
capReached = true;
overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
tokenAmount = tokenAmount.sub(overflowTokens);
refundWeiAmount = overflowTokens.div(rate);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
weiRaised = weiRaised.add(investedWeiAmount);
tokensMinted = tokensMinted.add(tokenAmount);
TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
token.mint(_beneficiary, tokenAmount);
if (capReached || overMaxInvestmentAllowed) {
msg.sender.transfer(refundWeiAmount);
wallet.transfer(investedWeiAmount);
forwardFunds();
}
}
function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
require(isWhitelisted[msg.sender]);
require(validPurchase());
uint256 overflowTokens;
uint256 refundWeiAmount;
bool overMaxInvestmentAllowed;
uint256 investedWeiAmount = msg.value;
uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
if (totalInvestedWeiAmount > maxContributionInWei) {
overMaxInvestmentAllowed = true;
refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
uint256 tokenAmount = investedWeiAmount.mul(rate);
if (tempMintedTokens >= CROWDSALE_TOKENS) {
capReached = true;
overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
tokenAmount = tokenAmount.sub(overflowTokens);
refundWeiAmount = overflowTokens.div(rate);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
weiRaised = weiRaised.add(investedWeiAmount);
tokensMinted = tokensMinted.add(tokenAmount);
TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
token.mint(_beneficiary, tokenAmount);
if (capReached || overMaxInvestmentAllowed) {
msg.sender.transfer(refundWeiAmount);
wallet.transfer(investedWeiAmount);
forwardFunds();
}
}
function buyTokens(address _beneficiary) public payable onlyCrowdsalePhase onlyValidAddress(_beneficiary) {
require(isWhitelisted[msg.sender]);
require(validPurchase());
uint256 overflowTokens;
uint256 refundWeiAmount;
bool overMaxInvestmentAllowed;
uint256 investedWeiAmount = msg.value;
uint256 totalInvestedWeiAmount = investedWeiAmount.add(totalInvestedPerAddress[msg.sender]);
if (totalInvestedWeiAmount > maxContributionInWei) {
overMaxInvestmentAllowed = true;
refundWeiAmount = totalInvestedWeiAmount.sub(maxContributionInWei);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
uint256 tokenAmount = investedWeiAmount.mul(rate);
if (tempMintedTokens >= CROWDSALE_TOKENS) {
capReached = true;
overflowTokens = tempMintedTokens.sub(CROWDSALE_TOKENS);
tokenAmount = tokenAmount.sub(overflowTokens);
refundWeiAmount = overflowTokens.div(rate);
investedWeiAmount = investedWeiAmount.sub(refundWeiAmount);
}
weiRaised = weiRaised.add(investedWeiAmount);
tokensMinted = tokensMinted.add(tokenAmount);
TokenPurchase(msg.sender, _beneficiary, investedWeiAmount, tokenAmount);
totalInvestedPerAddress[msg.sender] = totalInvestedPerAddress[msg.sender].add(investedWeiAmount);
token.mint(_beneficiary, tokenAmount);
if (capReached || overMaxInvestmentAllowed) {
msg.sender.transfer(refundWeiAmount);
wallet.transfer(investedWeiAmount);
forwardFunds();
}
}
} else {
function closeCrowdsale() public onlyOwner onlyCrowdsalePhase {
isCrowdsaleOver = true;
}
function finalize() public onlyOwner onlyCrowdSaleOver {
MintableToken(token).finishMinting();
PausableToken(token).unpause();
}
function mintTeamTokens() private {
token.mint(beneficiaryWallet, TEAM_TOKENS0);
TokenVesting newVault1 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_2Y, false);
token.mint(address(newVault1), TEAM_TOKENS1);
TokenVesting newVault2 = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
token.mint(address(newVault2), TEAM_TOKENS2);
}
function mintCommunityTokens() private {
TokenVesting newVault = new TokenVesting(beneficiaryWallet, now, 0, VESTING_DURATION_4Y, false);
token.mint(address(newVault), COMMUNITY_TOKENS);
}
function validPurchase() internal view respectCrowdsaleCap(0) returns (bool) {
require(!capReached);
require(totalInvestedPerAddress[msg.sender] < maxContributionInWei);
return super.validPurchase();
}
}
| 1,044,070 | [
1,
3767,
309,
1758,
353,
2935,
358,
2198,
395,
1699,
21103,
358,
10734,
471,
6932,
13608,
6170,
635,
3301,
9484,
21103,
848,
506,
444,
471,
22349,
635,
3410,
16,
3229,
3301,
9484,
854,
3323,
364,
13553,
732,
1707,
331,
10100,
17662,
2413,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
490,
5088,
39,
492,
2377,
5349,
353,
14223,
6914,
16,
385,
492,
2377,
5349,
288,
203,
203,
203,
565,
2254,
5034,
1071,
5381,
776,
11027,
1360,
67,
24951,
67,
24,
61,
273,
1059,
11387,
31,
203,
565,
2254,
5034,
1071,
5381,
776,
11027,
1360,
67,
24951,
67,
22,
61,
273,
576,
11387,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
353,
18927,
329,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
353,
1318,
31,
203,
203,
565,
2254,
5034,
1071,
943,
442,
4027,
382,
3218,
77,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
2078,
3605,
3149,
2173,
1887,
31,
203,
203,
565,
1758,
1071,
27641,
74,
14463,
814,
16936,
31,
203,
203,
565,
1758,
1071,
5927,
58,
10100,
22,
21945,
31,
203,
565,
1758,
1071,
5927,
58,
10100,
24,
21945,
31,
203,
565,
1758,
1071,
19833,
58,
10100,
24,
21945,
31,
203,
203,
565,
1426,
1071,
25249,
492,
2377,
5349,
4851,
31,
203,
203,
565,
871,
27707,
1318,
12,
2867,
3301,
16,
1426,
2695,
1769,
203,
565,
871,
18346,
5349,
49,
474,
329,
12,
2867,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
1147,
6275,
1769,
203,
565,
871,
27707,
3605,
395,
280,
18927,
310,
12,
2867,
8808,
2198,
395,
280,
16,
1426,
26944,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
24,
18,
2643,
31,
203,
565,
9606,
1338,
1318,
1435,
288,
203,
3639,
2583,
12,
291,
1318,
63,
3576,
18,
15330,
19226,
203,
3639,
389,
31,
203,
565,
289,
2
] |
pragma solidity ^0.7.0;
// import files from common directory
import { TokenInterface , MemoryInterface } from "../common/interfaces.sol";
import { Stores } from "../common/stores.sol";
interface AccountInterface {
function enable(address) external;
function disable(address) external;
}
interface DydxFlashInterface {
function initiateFlashLoan(address _token, uint256 _amount, bytes calldata data) external;
}
abstract contract FlashLoanResolver is Stores {
event LogDydxFlashLoan(address indexed token, uint256 tokenAmt);
/**
* @dev Return ethereum address
*/
function getDydxLoanAddr() internal pure returns (address) {
return address(0); // check9898 - change to dydx flash contract address
}
function getWethAddr() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
/**
* @dev Borrow Flashloan and Cast spells.
* @param token Token Address.
* @param tokenAmt Token Amount.
* @param data targets & data for cast.
*/
function borrowAndCast(address token, uint tokenAmt, bytes memory data) public payable {
AccountInterface(address(this)).enable(getDydxLoanAddr());
address _token = token == ethAddr ? getWethAddr() : token;
DydxFlashInterface(getDydxLoanAddr()).initiateFlashLoan(_token, tokenAmt, data);
AccountInterface(address(this)).disable(getDydxLoanAddr());
emit LogDydxFlashLoan(token, tokenAmt);
}
}
contract ConnectDydxFlashLoan is FlashLoanResolver {
string public constant name = "dydx-flashloan-v1";
}
| * @dev Borrow Flashloan and Cast spells. @param token Token Address. @param tokenAmt Token Amount. @param data targets & data for cast./ | function borrowAndCast(address token, uint tokenAmt, bytes memory data) public payable {
AccountInterface(address(this)).enable(getDydxLoanAddr());
address _token = token == ethAddr ? getWethAddr() : token;
DydxFlashInterface(getDydxLoanAddr()).initiateFlashLoan(_token, tokenAmt, data);
AccountInterface(address(this)).disable(getDydxLoanAddr());
emit LogDydxFlashLoan(token, tokenAmt);
}
| 12,782,021 | [
1,
38,
15318,
15014,
383,
304,
471,
19782,
22377,
87,
18,
225,
1147,
3155,
5267,
18,
225,
1147,
31787,
3155,
16811,
18,
225,
501,
5774,
473,
501,
364,
4812,
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,
29759,
1876,
9735,
12,
2867,
1147,
16,
2254,
1147,
31787,
16,
1731,
3778,
501,
13,
1071,
8843,
429,
288,
203,
3639,
6590,
1358,
12,
2867,
12,
2211,
13,
2934,
7589,
12,
588,
40,
93,
13437,
1504,
304,
3178,
10663,
203,
203,
3639,
1758,
389,
2316,
273,
1147,
422,
13750,
3178,
692,
13876,
546,
3178,
1435,
294,
1147,
31,
203,
203,
3639,
463,
93,
13437,
11353,
1358,
12,
588,
40,
93,
13437,
1504,
304,
3178,
1435,
2934,
2738,
3840,
11353,
1504,
304,
24899,
2316,
16,
1147,
31787,
16,
501,
1769,
203,
203,
3639,
6590,
1358,
12,
2867,
12,
2211,
13,
2934,
8394,
12,
588,
40,
93,
13437,
1504,
304,
3178,
10663,
203,
203,
3639,
3626,
1827,
40,
93,
13437,
11353,
1504,
304,
12,
2316,
16,
1147,
31787,
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
] |
./full_match/3/0xAcEFfcedB82101De103d2ff802f3D1ab330548e1/sources/contracts/4_Market.sol | Offer can only be cacelled by the seller while it is pending and there is no buyer If the offered amount increases, deposit more Tokens If the offered amount decreases, return Tokens | function updateOffer(uint _id, address _offeredContract, address _wantedContract, uint _offeredAmount, uint _wantedAmount) public {
require(msg.sender == idToOffer[_id].seller, "You are not the owner of the offer");
require(idToOffer[_id].status == 0 && idToOffer[_id].buyer == address(0), "The offer has already been accepted");
if (idToOffer[_id].offeredAmount < _offeredAmount) {
ERC20 token = ERC20(_offeredContract);
require(token.balanceOf(msg.sender) >= _offeredAmount, "Insufficient Token balance");
require(token.approve(address(this), _offeredAmount), "Token approve failed");
require(token.allowance(msg.sender, address(this)) >= _offeredAmount, "Insufficient Token allowance");
require(token.transferFrom(msg.sender, address(this), _offeredAmount), "Token transfer failed");
token.approve(address(this), amountToDeposit);
token.transferFrom(msg.sender, address(this), amountToDeposit);
ERC20 token = ERC20(idToOffer[_id].offeredContract);
token.transferFrom(address(this), msg.sender, amountToReturn);
}
idToOffer[_id] = Offer(_id, _offeredAmount, _wantedAmount, msg.sender, address(0), _offeredContract, _wantedContract, 0);
}
| 8,210,926 | [
1,
10513,
848,
1338,
506,
276,
1077,
292,
1259,
635,
326,
29804,
1323,
518,
353,
4634,
471,
1915,
353,
1158,
27037,
971,
326,
10067,
329,
3844,
7033,
3304,
16,
443,
1724,
1898,
13899,
971,
326,
10067,
329,
3844,
23850,
3304,
16,
327,
13899,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
10513,
12,
11890,
389,
350,
16,
1758,
389,
23322,
329,
8924,
16,
1758,
389,
25861,
8924,
16,
2254,
389,
23322,
329,
6275,
16,
2254,
389,
25861,
6275,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
612,
774,
10513,
63,
67,
350,
8009,
1786,
749,
16,
315,
6225,
854,
486,
326,
3410,
434,
326,
10067,
8863,
203,
3639,
2583,
12,
350,
774,
10513,
63,
67,
350,
8009,
2327,
422,
374,
597,
612,
774,
10513,
63,
67,
350,
8009,
70,
16213,
422,
1758,
12,
20,
3631,
315,
1986,
10067,
711,
1818,
2118,
8494,
8863,
203,
540,
203,
3639,
309,
261,
350,
774,
10513,
63,
67,
350,
8009,
23322,
329,
6275,
411,
389,
23322,
329,
6275,
13,
288,
203,
2398,
203,
5411,
4232,
39,
3462,
1147,
273,
4232,
39,
3462,
24899,
23322,
329,
8924,
1769,
203,
5411,
2583,
12,
2316,
18,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
389,
23322,
329,
6275,
16,
315,
5048,
11339,
3155,
11013,
8863,
203,
5411,
2583,
12,
2316,
18,
12908,
537,
12,
2867,
12,
2211,
3631,
389,
23322,
329,
6275,
3631,
315,
1345,
6617,
537,
2535,
8863,
203,
5411,
2583,
12,
2316,
18,
5965,
1359,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3719,
1545,
389,
23322,
329,
6275,
16,
315,
5048,
11339,
3155,
1699,
1359,
8863,
203,
5411,
2583,
12,
2316,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
23322,
329,
6275,
3631,
315,
1345,
7412,
2535,
8863,
203,
2398,
203,
5411,
1147,
18,
12908,
537,
12,
2867,
2
] |
pragma solidity ^0.5.12;
contract Election{
//model candidate
//state variables dont have underscore
//local variables prefixed with underscore
struct Candidate {
uint id;
string name;
uint voteCount;
}
//store accounts that have voted
mapping(address => bool) public voters;
//uint= unsigned integer
mapping(uint => Candidate) public candidates; //candidates function generated to fetch candidate
//uint =key Candidate = value //adding candidate changes the state of the contract
uint public candidatesCount; //cannot find number of candidates nor iterate over mapping
//voted event
//constructor
constructor () public { //constructor will run when there is a deploy
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate (string memory _name) private {
candidatesCount++;
candidates[candidatesCount] = Candidate(candidatesCount,_name,0);
}
function vote (uint _candidateId) public {
//record that voter has voted
//msg.sender //function receives meta data as another argument (msg)
//sender calling this function will send gas and gas is used only for require() and for
//other statements gas is refunded to the sender
//require that they havent voted before
require(!voters[msg.sender]); //if condition = true then following code will be evaluated
//require a valid candidate
require(_candidateId > 0 && _candidateId <= candidatesCount);
//record that voter has voted
voters[msg.sender] = true; //key is address and value is true
//update candidate vote count
candidates[_candidateId].voteCount++;
}
} | model candidatestate variables dont have underscorelocal variables prefixed with underscore | contract Election{
struct Candidate {
uint id;
string name;
uint voteCount;
}
addCandidate("Candidate 2");
mapping(address => bool) public voters;
addCandidate("Candidate 1");
}
| 15,820,256 | [
1,
2284,
4225,
270,
395,
340,
3152,
14046,
1240,
13677,
3729,
3152,
12829,
598,
13677,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
512,
942,
95,
203,
565,
1958,
385,
8824,
288,
203,
3639,
2254,
612,
31,
203,
3639,
533,
508,
31,
203,
3639,
2254,
12501,
1380,
31,
203,
565,
289,
203,
203,
203,
377,
203,
203,
3639,
527,
11910,
2932,
11910,
576,
8863,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
331,
352,
414,
31,
203,
377,
203,
377,
203,
3639,
527,
11910,
2932,
11910,
404,
8863,
7010,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x5BC253b9fE40d92f8a01e62899A77ae124F68C5a/sources/contracts/NestStaking.sol | @dev To ensure that all of governance-addresses be consist with each other governance = INestPool(C_NestPool).governance(); | function loadGovernance() override external
{
}
| 12,496,821 | [
1,
774,
3387,
716,
777,
434,
314,
1643,
82,
1359,
17,
13277,
506,
7111,
598,
1517,
1308,
314,
1643,
82,
1359,
273,
2120,
395,
2864,
12,
39,
67,
50,
395,
2864,
2934,
75,
1643,
82,
1359,
5621,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
1262,
43,
1643,
82,
1359,
1435,
3849,
3903,
7010,
565,
288,
7010,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./IBox.sol";
import "./BoxStorage.sol";
import "./OnlyDelegateCall.sol";
/**
* @title Box with functions to store, withdraw, transferBetweenBoxes and destroy
* @notice This contract is meant to be delegateCalled by a contract inheriting from BoxExternal
* @notice This contract forbid reception of ERC1155 and ERC721
* @notice Don't send ERC20 to this contract !
*/
contract BoxBase is IBox, BoxStorage, Context, OnlyDelegateCall {
/**
* @dev Store tokens inside a box
* @notice allowance for the tokens must be done to the BoxExternal contract
*
* @param boxId id of the box
* @param erc20s list of erc20 to store
* @param erc721s list of erc721 to store
* @param erc1155s list of erc1155 to store
*/
function store(
uint256 boxId,
ERC20TokenInfos[] calldata erc20s,
ERC721TokenInfos[] calldata erc721s,
ERC1155TokenInfos[] calldata erc1155s
) external payable override onlyDelegateCall {
// store ETH tokens
_storeEth(boxId, msg.value);
// store ERC721 tokens
for (uint256 j = 0; j < erc721s.length; j++) {
_storeErc721(boxId, erc721s[j].addr, erc721s[j].ids);
}
// store ERC20 tokens
for (uint256 j = 0; j < erc20s.length; j++) {
_storeErc20(boxId, erc20s[j].addr, erc20s[j].amount);
}
// store ERC1155 tokens
for (uint256 j = 0; j < erc1155s.length; j++) {
_storeErc1155(
boxId,
erc1155s[j].addr,
erc1155s[j].ids,
erc1155s[j].amounts
);
}
emit Store(boxId, msg.value, erc20s, erc721s, erc1155s);
}
/**
* @dev Withdraw tokens from a box to an address
*
* @param boxId id of the box
* @param ethAmount amount of eth to withdraw
* @param erc20s list of erc20 to withdraw
* @param erc721s list of erc721 to withdraw
* @param erc1155s list of erc1155 to withdraw
* @param to address of reception
*/
function withdraw(
uint256 boxId,
uint256 ethAmount,
ERC20TokenInfos[] calldata erc20s,
ERC721TokenInfos[] calldata erc721s,
ERC1155TokenInfos[] calldata erc1155s,
address payable to
) external override onlyDelegateCall {
// withdraw ETH tokens
_withdrawEth(boxId, ethAmount, to);
// withdraw ERC721 tokens
for (uint256 j = 0; j < erc721s.length; j++) {
_withdrawERC721(boxId, erc721s[j].addr, erc721s[j].ids, to);
}
// withdraw ERC20 tokens
for (uint256 j = 0; j < erc20s.length; j++) {
_withdrawERC20(boxId, erc20s[j].addr, erc20s[j].amount, to);
}
// withdraw ERC1155 tokens
for (uint256 j = 0; j < erc1155s.length; j++) {
_withdrawERC1155(
boxId,
erc1155s[j].addr,
erc1155s[j].ids,
erc1155s[j].amounts,
to
);
}
emit Withdraw(boxId, ethAmount, erc20s, erc721s, erc1155s, to);
}
/**
* @dev Transfer tokens from a box to another
*
* @param srcBoxId source box
* @param destBoxId destination box
* @param ethAmount amount of eth to transfer
* @param erc20s list of erc20 to transfer
* @param erc721s list of erc721 to transfer
* @param erc1155s list of erc1155 to transfer
*/
function transferBetweenBoxes(
uint256 srcBoxId,
uint256 destBoxId,
uint256 ethAmount,
ERC20TokenInfos[] calldata erc20s,
ERC721TokenInfos[] calldata erc721s,
ERC1155TokenInfos[] calldata erc1155s
) external override onlyDelegateCall {
// transferBetweenBoxes Ethers
_transferEthBetweenBoxes(srcBoxId, destBoxId, ethAmount);
// transferBetweenBoxes ERC721 tokens
_transferErc721BetweenBoxes(srcBoxId, destBoxId, erc721s);
// transferBetweenBoxes ERC20 tokens
_transferErc20BetweenBoxes(srcBoxId, destBoxId, erc20s);
// transferBetweenBoxes ERC1155 tokens
_transferErc1155BetweenBoxes(srcBoxId, destBoxId, erc1155s);
emit TransferBetweenBoxes(
srcBoxId,
destBoxId,
ethAmount,
erc20s,
erc721s,
erc1155s
);
}
/**
* @dev Destroy a box
*
* @param boxId id of the box
* @param ethAmount amount of eth to withdraw
* @param erc20ToWithdraw list of erc20 to withdraw
* @param erc721ToWithdraw list of erc721 to withdraw
* @param erc1155ToWithdraw list of erc1155 to withdraw
* @param to address of reception
*/
function destroy(
uint256 boxId,
uint256 ethAmount,
ERC20TokenInfos[] calldata erc20ToWithdraw,
ERC721TokenInfos[] calldata erc721ToWithdraw,
ERC1155TokenInfos[] calldata erc1155ToWithdraw,
address payable to
) external override onlyDelegateCall {
// destroy the box
destroyedBoxes[boxId] = true;
emit Destroyed(boxId);
// withdraw ETH tokens
_withdrawEth(boxId, ethAmount, to);
// withdraw ERC721 tokens
for (uint256 j = 0; j < erc721ToWithdraw.length; j++) {
_withdrawERC721(
boxId,
erc721ToWithdraw[j].addr,
erc721ToWithdraw[j].ids,
to
);
}
// withdraw ERC20 tokens
for (uint256 j = 0; j < erc20ToWithdraw.length; j++) {
_withdrawERC20(
boxId,
erc20ToWithdraw[j].addr,
erc20ToWithdraw[j].amount,
to
);
}
// withdraw ERC1155 tokens
for (uint256 j = 0; j < erc1155ToWithdraw.length; j++) {
_withdrawERC1155(
boxId,
erc1155ToWithdraw[j].addr,
erc1155ToWithdraw[j].ids,
erc1155ToWithdraw[j].amounts,
to
);
}
emit Withdraw(
boxId,
ethAmount,
erc20ToWithdraw,
erc721ToWithdraw,
erc1155ToWithdraw,
to
);
}
/**
* @dev Get the balance of ethers in a box
* @notice will always revert
*/
function EthBalanceOf(uint256) public pure override returns (uint256) {
revert();
}
/**
* @dev Get the balance of an erc20 token in a box
* @notice will always revert
*/
function erc20BalanceOf(uint256, address)
public
pure
override
returns (uint256)
{
revert();
}
/**
* @dev Get the balance of an erc1155 token in a box
* @notice will always revert
*/
function erc1155BalanceOf(
uint256,
address,
uint256
) public pure override returns (uint256) {
revert();
}
/**
* @dev Check if an ERC721 token is in a box
* @notice will always revert
*/
function erc721BalanceOf(
uint256,
address,
uint256
) public pure override returns (uint256) {
revert();
}
/**
* @dev Handles the receipt of ERC1155 token types
* @notice will always revert
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) public pure override returns (bytes4) {
revert();
}
/**
* @dev Handles the receipt of a multiple ERC1155 token types
* @notice will always revert
*/
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) public pure override returns (bytes4) {
revert();
}
/**
* @dev Handles the receipt of a multiple ERC721 token types
* @notice will always revert
*/
function onERC721Received(
address,
address,
uint256,
bytes calldata
) public pure override returns (bytes4) {
revert();
}
/**
* @dev Withdraw ethers from a box to an address
*
* @param boxId id of the box
* @param amount amount of eth to withdraw
*/
function _withdrawEth(
uint256 boxId,
uint256 amount,
address payable to
) private {
// update the box and check if the amount in the box in sufficient
_indexedEth[boxId] -= amount;
(bool success, ) = payable(to).call{value: amount}("");
require(success);
}
/**
* @dev Withdraw erc721 tokens from a box to an address
*
* @param boxId id of the box
* @param tokenAddress address of the token
* @param tokenIds list of token ids to withdraw
* @param to address of reception
*/
function _withdrawERC721(
uint256 boxId,
address tokenAddress,
uint256[] calldata tokenIds,
address to
) private {
IERC721 token = IERC721(tokenAddress);
for (uint256 k = 0; k < tokenIds.length; k++) {
uint256 tokenId = tokenIds[k];
bytes32 index = keccak256(
abi.encodePacked(boxId, tokenAddress, tokenId)
);
// check if the token is in the box
require(_indexedTokens[index] == 1, "e6");
// update balance to avoid reentrancy
delete _indexedTokens[index];
// transfer the token to the owner of the box
token.transferFrom(address(this), to, tokenId);
}
}
/**
* @dev Withdraw erc20 tokens from a box to an address
*
* @param boxId id of the box
* @param tokenAddress address of the token
* @param amountToWithdraw amount to withdraw
* @param to address of reception
*/
function _withdrawERC20(
uint256 boxId,
address tokenAddress,
uint256 amountToWithdraw,
address to
) private {
bytes32 index = keccak256(abi.encodePacked(boxId, tokenAddress));
// update the box and check if the amount in the box is sufficient
_indexedTokens[index] -= amountToWithdraw;
// Safely transfer the token
IERC20 token = IERC20(tokenAddress);
SafeERC20.safeTransfer(token, to, amountToWithdraw);
}
/**
* @dev Withdraw erc1155 tokens from a box to an address
*
* @param boxId id of the box
* @param tokenAddress address of the token
* @param tokenIds list of token ids to withdraw
* @param amounts amount to withdraw for each token id
* @param to address of reception
*/
function _withdrawERC1155(
uint256 boxId,
address tokenAddress,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
address to
) private {
for (uint256 j = 0; j < tokenIds.length; j++) {
bytes32 index = keccak256(
abi.encodePacked(boxId, tokenAddress, tokenIds[j])
);
// update the box and check if the amount in the box in sufficient
_indexedTokens[index] -= amounts[j];
}
IERC1155 token = IERC1155(tokenAddress);
token.safeBatchTransferFrom(address(this), to, tokenIds, amounts, "");
}
/**
* @dev store eth inside a box
*
* @param boxId id of the box
* @param amount amount of eth to store
*/
function _storeEth(uint256 boxId, uint256 amount) private {
// update the box
_indexedEth[boxId] += amount;
}
/**
* @dev store erc721 tokens inside a box
*
* @param boxId id of the box
* @param tokenAddress address of the token
* @param tokenIds list of token ids to store
*/
function _storeErc721(
uint256 boxId,
address tokenAddress,
uint256[] calldata tokenIds
) private {
// Avoid storing a box in a box
require(tokenAddress != address(this), "e20");
IERC721 token = IERC721(tokenAddress);
for (uint256 j = 0; j < tokenIds.length; j++) {
bytes32 index = keccak256(
abi.encodePacked(boxId, tokenAddress, tokenIds[j])
);
require(_indexedTokens[index] == 0, "e1");
// update the box
_indexedTokens[index] = 1;
// transfer the token to this very contract
token.safeTransferFrom(_msgSender(), address(this), tokenIds[j]);
}
}
/**
* @dev store erc20 tokens in a box
*
* @param boxId id of the box
* @param tokenAddress address of the token
* @param amount amount to store
*/
function _storeErc20(
uint256 boxId,
address tokenAddress,
uint256 amount
) private {
bytes32 index = keccak256(abi.encodePacked(boxId, tokenAddress));
// update the box
_indexedTokens[index] += amount;
IERC20 token = IERC20(tokenAddress);
// Safely transfer the token to this very contract
SafeERC20.safeTransferFrom(token, _msgSender(), address(this), amount);
}
/**
* @dev store erc1155 tokens in a box
*
* @param boxId id of the box
* @param tokenAddress address of the token
* @param tokenIds list of token ids to store
* @param amounts amount to store for each token id
*/
function _storeErc1155(
uint256 boxId,
address tokenAddress,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) private {
for (uint256 j = 0; j < tokenIds.length; j++) {
bytes32 index = keccak256(
abi.encodePacked(boxId, tokenAddress, tokenIds[j])
);
// update the box
_indexedTokens[index] += amounts[j];
}
IERC1155 token = IERC1155(tokenAddress);
// transfer the token to this very contract
token.safeBatchTransferFrom(
_msgSender(),
address(this),
tokenIds,
amounts,
""
);
}
/**
* @dev transfer ethers from a box to another
*
* @param srcBoxId id of the source box
* @param srcBoxId id of the destination box
* @param ethAmount amount of eth to transfer
*/
function _transferEthBetweenBoxes(
uint256 srcBoxId,
uint256 destBoxId,
uint256 ethAmount
) private {
// remove from the source box
_indexedEth[srcBoxId] -= ethAmount;
// destination index
_indexedEth[destBoxId] += ethAmount;
}
/**
* @dev transfer erc721 from a box to another
*
* @param srcBoxId id of the source box
* @param srcBoxId id of the destination box
* @param erc721s list of erc721s token to transfer
*/
function _transferErc721BetweenBoxes(
uint256 srcBoxId,
uint256 destBoxId,
ERC721TokenInfos[] calldata erc721s
) private {
for (uint256 j = 0; j < erc721s.length; j++) {
for (uint256 k = 0; k < erc721s[j].ids.length; k++) {
// source index
bytes32 index = keccak256(
abi.encodePacked(
srcBoxId,
erc721s[j].addr,
erc721s[j].ids[k]
)
);
require(_indexedTokens[index] == 1, "e16");
// remove from the source box
delete _indexedTokens[index];
// destination index
index = keccak256(
abi.encodePacked(
destBoxId,
erc721s[j].addr,
erc721s[j].ids[k]
)
);
// add to the destination box
_indexedTokens[index] = 1;
}
}
}
/**
* @dev transfer erc20 from a box to another
*
* @param srcBoxId id of the source box
* @param srcBoxId id of the destination box
* @param erc20s list of erc20s token to transfer
*/
function _transferErc20BetweenBoxes(
uint256 srcBoxId,
uint256 destBoxId,
ERC20TokenInfos[] calldata erc20s
) private {
for (uint256 j = 0; j < erc20s.length; j++) {
// source index
bytes32 index = keccak256(
abi.encodePacked(srcBoxId, erc20s[j].addr)
);
// remove from the source box
_indexedTokens[index] -= erc20s[j].amount;
// destination index
index = keccak256(abi.encodePacked(destBoxId, erc20s[j].addr));
// add to the destination box
_indexedTokens[index] += erc20s[j].amount;
}
}
/**
* @dev transfer erc1155 from a box to another
*
* @param srcBoxId id of the source box
* @param srcBoxId id of the destination box
* @param erc1155s list of erc1155 tokens to transfer
*/
function _transferErc1155BetweenBoxes(
uint256 srcBoxId,
uint256 destBoxId,
ERC1155TokenInfos[] calldata erc1155s
) private {
for (uint256 j = 0; j < erc1155s.length; j++) {
for (uint256 k = 0; k < erc1155s[j].ids.length; k++) {
// source index
bytes32 index = keccak256(
abi.encodePacked(
srcBoxId,
erc1155s[j].addr,
erc1155s[j].ids[k]
)
);
// remove from the source box
_indexedTokens[index] -= erc1155s[j].amounts[k];
// destination index
index = keccak256(
abi.encodePacked(
destBoxId,
erc1155s[j].addr,
erc1155s[j].ids[k]
)
);
// add to the destination box
_indexedTokens[index] += erc1155s[j].amounts[k];
}
}
}
}
| * @dev store eth inside a box @param boxId id of the box @param amount amount of eth to store/ update the box | function _storeEth(uint256 boxId, uint256 amount) private {
_indexedEth[boxId] += amount;
}
| 979,301 | [
1,
2233,
13750,
4832,
279,
3919,
225,
3919,
548,
612,
434,
326,
3919,
225,
3844,
3844,
434,
13750,
358,
1707,
19,
1089,
326,
3919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2233,
41,
451,
12,
11890,
5034,
3919,
548,
16,
2254,
5034,
3844,
13,
3238,
288,
203,
3639,
389,
19626,
41,
451,
63,
2147,
548,
65,
1011,
3844,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
import "./ecOps.sol";
contract dkg {
/**
* DKG phases (optimistic case):
*
* 0) Deploy the contract with a threshold (t), number of participants (n)
* and deposit in Wei.
*
* 1) Enrollment - Each of the participants sends a deposit and a public key
* address (for encryption purpose) that he owns (i.e., has the corresponding
* secret key). At the end of the enrollment each participant receives an
* unique index (1,...,n) that would be used with his identity for the rest
* of the DKG protocol and the threshold signature scheme.
*
* (not on the contract) - each participant generates t+1 random sampled
* coefficients from the (mod q) field.
*
* 2) Each of the participants sends its public commitments (the generator
* exponentiated with t+1 coefficients) and encrypted private commitments
* for all of the other particpants.
*
* After all have validly committed each of the participant can take the
* committed data and locally compute the followings:
* a) its own secret key and public key;
* b) the public keys for the rest of the participants;
* c) the group's public key (no one would know the corresponding secret
* key);
* With the above data each participant is able to sign, verify signature-
* shares and reconstruct from t+1 signatures the group signature.
*
*
*
* In case one (or more) of the participants deviates from the instructions
* of the protocol, we enable the other participants to file a complaint to
* the contract. Such a complaint would terminate the DKG protocol with a
* failure. Once a complaint is filed, a code is run to check the validity of
* the complaint. When done the code decides which participant's deposit to
* slash and divide it among the other participants ("code is law").
*
* Each participant can send a complaint tx about one of the followings:
* a) 2 distinct participants offered the same public commitment
(one is enough). (TODO)
* b) Some participant offered invalid commitment (invalid is:
* duplicated, insufficient, unmatching commitments G1 to G2)
* c) Umatched private and public commitments.
* d) Time out.
*
*/
/**
* Important note: at this point this contract purpose is as a
* POC only, therefore its security is unreliable.
*/
struct Participant {
address ethPk; // Ethereum pk
uint256[2] encPk; // pk for encryption
mapping (uint16 => uint256[2]) publicCommitmentsG1; // coefficient index to commitment
mapping (uint16 => uint256[4]) publicCommitmentsG2;
// TODO: should be encrypted (and possibly off chain).
mapping (uint16 => uint256) encPrivateCommitments; // node's index to its commitment
bool isCommitted;
}
enum Phase { Enrollment, Commit, PostCommit, EndSuccess, EndFail } // start from 0
event PhaseChange(
Phase phase
);
event NewCommit(
uint16 committerIndex,
uint256[] pubCommitG1,
uint256[] pubCommitG2,
uint256[] prvCommit
);
event ParticipantJoined(
uint16 index
);
Phase public curPhase;
//uint256 public constant a = 0;
//uint256 public constant b = 3;
// G1 generator (on the curve)
uint256[2] public g1 = [
0x0000000000000000000000000000000000000000000000000000000000000001,
0x0000000000000000000000000000000000000000000000000000000000000002
];
// G2 generator (on the curve)
uint256[4] public g2 = [
0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed,
0x90689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
];
uint256 public depositWei;
uint16 public t; // threshold
uint16 public n; // numer of participants;
uint16 public curN; // current num of participants
uint16 public curNumCommittedLeft; // current num of participants that haven't committed
uint256 public phaseStart;
uint256 public constant joinTimeout = 12;
uint256 public constant commitTimeout = 11;
uint256 public constant postCommitTimeout = 5;
// mapping from node's index to a participant
mapping (uint16 => Participant) public participants;
constructor(uint16 threshold, uint16 numParticipants, uint deposit) public
{
t = threshold;
n = numParticipants;
curNumCommittedLeft = numParticipants;
depositWei = deposit;
curPhase = Phase.Enrollment;
require(n > t && t > 0, "wrong input");
phaseStart = block.number;
}
modifier checkDeposit() {
require(msg.value == depositWei, "wrong deposit");
_;
}
modifier checkAuthorizedSender(uint16 index) {
require(participants[index].ethPk == msg.sender, "not authorized sender");
_;
}
modifier beFalse(bool term) {
require(!term);
_;
}
modifier inPhase(Phase phase) {
require(curPhase == phase, "wrong phase");
_;
}
modifier notInPhase(Phase phase) {
require(curPhase != phase, "wrong phase");
_;
}
// Join the DKG (enrollment - phase 1).
// A point on G1 that represents this participant's pk for encryption have
// to be published. The publisher have to know the secret that generates
// this point.
function join(uint256[2] encPk)
checkDeposit()
inPhase(Phase.Enrollment)
external payable
returns(uint16 index)
{
// TODO: check pk
uint16 cn = curN;
address sender = msg.sender;
// Check the pk isn't registered already
for(uint16 i = 1; i <= cn; i++) {
require(participants[i].ethPk != sender, "already joined");
}
cn++;
participants[cn] = Participant({ethPk: sender, encPk: encPk, isCommitted: false});
curN = cn;
if(cn == 1) {
phaseStart = block.number;
}
// Abort if capacity on participants was reached
if(cn == n) {
curPhase = Phase.Commit;
emit PhaseChange(Phase.Commit);
}
emit ParticipantJoined(cn);
return cn;
}
// Send commitments (phase 2).
//
// pubCommitG1 is composed of t+1 commitments to local randomly sampled
// coefficients. Each commitment should be on the G1 curve (affine
// coordinates) and therefore it has 2 coordinates. Thus, the input array
// is of size (2t+2) and the i'th commitment will be in indices (2i) and
// (2i+1).
//
// pubCommitG2 is composed of t+1 commitments to same sampled coefficients
// from pubCommitG1. Each commitment should be on the G2 curve (affine
// coordinates) and therefore it has 4 coordinates. Thus, the input array
// is of size (4t+4) and the i'th commitment will be in indices (4i),(4i+1),
// (4i+2),(4i+3).
//
// prCommit is an array of size n, where the first index matches the
// first participant (participant index 1) and so forth. The commitment
// is a calculation on the localy generated polynomial in the particpant's
// index. This calculation is encrypted by the recevier pk for encryption.
// The senderIndex private commitment is ignored and can be anything
// (but can't be skipped).
//
// Note that this function does not verifies the committed data, it
// should be done outside of this contract scope. In case of an
// invalid committed data use complaints.
function commit(uint16 senderIndex, uint256[] pubCommitG1,
uint256[] pubCommitG2, uint256[] encPrCommit)
inPhase(Phase.Commit)
checkAuthorizedSender(senderIndex)
beFalse(participants[senderIndex].isCommitted)
external
{
// TODO: phase timeout, make prCommit encrypted, verify sender
// index matches the sender's address.
assignCommitments(senderIndex, pubCommitG1, pubCommitG2, encPrCommit);
uint16 committedNumLeft = curNumCommittedLeft - 1;
curNumCommittedLeft = committedNumLeft;
if(committedNumLeft == 0) {
curPhase = Phase.PostCommit;
phaseStart = block.number;
emit PhaseChange(Phase.PostCommit);
}
}
// Assigns the commitments to the sender with index of senderIndex.
function assignCommitments(uint16 senderIndex, uint256[] pubCommitG1,
uint256[] pubCommitG2, uint256[] prCommit)
internal
{
// TODO: consider merging the following loops to save gas
uint16 nParticipants = n;
uint16 threshold = t;
// Verify input size
require(pubCommitG1.length == (threshold*2 + 2)
&& pubCommitG2.length == (threshold*4 + 4)
&& prCommit.length == nParticipants,
"input size invalid");
// Assign public commitments from G1 and G2
for(uint16 i = 0; i < (threshold+1); i++) {
participants[senderIndex].publicCommitmentsG1[i] = [pubCommitG1[2*i], pubCommitG1[2*i+1]];
participants[senderIndex].publicCommitmentsG2[i] = [
pubCommitG2[4*i], pubCommitG2[4*i+1], pubCommitG2[4*i+2], pubCommitG2[4*i+3]
];
}
// Assign private commitments
for(i = 1; i <= nParticipants; i++) {
if(senderIndex != i) {
participants[senderIndex].encPrivateCommitments[i] = prCommit[i-1];
}
}
participants[senderIndex].isCommitted = true;
emit NewCommit(senderIndex, pubCommitG1, pubCommitG2, prCommit);
}
// Call this when in Phase.PostCommit for more than postCommitTimeout
// blocks and no comlaint has to be made.
function postCommitTimedOut()
inPhase(Phase.PostCommit)
external
{
uint curBlockNum = block.number;
require(curBlockNum > (phaseStart+postCommitTimeout), "hasn't reached timeout yet");
curPhase = Phase.EndSuccess;
emit PhaseChange(Phase.EndSuccess);
slash(0);
}
// Call this when in Phase.Enrollment for more than joinTimeout
// blocks and not enough members have joined.
function joinTimedOut()
inPhase(Phase.Enrollment)
external
{
uint curBlockNum = block.number;
require(curBlockNum > (phaseStart+joinTimeout), "hasn't reached timeout yet");
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
slash(0);
}
// Call this when in Phase.Commit for more than commitTimeout
// blocks and not enough members have committed.
function commitTimedOut()
inPhase(Phase.Commit)
external
{
uint curBlockNum = block.number;
require(curBlockNum > (phaseStart+commitTimeout), "hasn't reached timeout yet");
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
slashUncommitted();
}
// Returns the group PK.
// This can only be performed after the DKG has ended. This
// means only when the current phase is Phase.End .
function getGroupPK()
inPhase(Phase.EndSuccess)
public view returns(uint256[2] groupPK)
{
uint16 nParticipants = n;
groupPK = participants[1].publicCommitmentsG1[0];
for(uint16 i = 2; i <= nParticipants; i++) {
groupPK = ecOps.ecadd(groupPK, participants[i].publicCommitmentsG1[0]);
}
}
////////////////
// Complaints //
////////////////
// A complaint on some public commit. If for some reason this
// function fails it will slash the complainer deposit! (unless some
// unauthorized address made the transaction or the wrong phase).
//
// The complaint should be called when the public commitments coming
// from the G1 group does not match to the ones from G2 group (using pairing).
function complaintPublicCommit(uint16 complainerIndex, uint16 accusedIndex,
uint16 pubCommitIndex)
checkAuthorizedSender(complainerIndex)
notInPhase(Phase.EndFail)
notInPhase(Phase.EndSuccess)
public
{
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
Participant storage accused = participants[accusedIndex];
if(!accused.isCommitted) {
slash(complainerIndex);
return;
}
if (ecOps.pairingCheck(accused.publicCommitmentsG1[pubCommitIndex],
g2, g1, accused.publicCommitmentsG2[pubCommitIndex])) {
slash(complainerIndex);
}
else {
slash(accusedIndex);
}
}
// A complaint on some private commitment. If for some reason this
// function fails it will slash the complainer deposit! (unless some
// unauthorized address made the transaction or the wrong phase).
//
// The complaint should be called when some private commitment does
// not match to the public commitment.
// The complainer has to publish the secret key from which its pk
// for encryption is derived.
function complaintPrivateCommit(uint16 complainerIndex,
uint16 accusedIndex,
uint256 complainerSk)
checkAuthorizedSender(complainerIndex)
notInPhase(Phase.EndFail)
notInPhase(Phase.EndSuccess)
public
{
// TODO: a check for edge cases has to be
// done (e.g., when no one has yet committed)
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
Participant storage accused = participants[accusedIndex];
if(!accused.isCommitted) {
slash(complainerIndex);
return;
}
if(!ecOps.isEqualPoints(participants[complainerIndex].encPk, ecOps.ecmul(g1, complainerSk))) {
slash(complainerIndex);
return;
}
uint256 prvCommit = uint256(decrypt(accused.encPk, complainerSk, bytes32(accused.encPrivateCommitments[complainerIndex])));
if (isPrvMatchPubCommit(complainerIndex, prvCommit, accused)) {
slash(complainerIndex);
}
else {
slash(accusedIndex);
}
}
function isPrvMatchPubCommit(uint16 complainerIndex, uint256 prvCommit, Participant storage accused)
view
internal
returns (bool isMatch)
{
uint256[2] memory temp;
uint256[2] memory RHS;
uint256[2] memory LHS = ecOps.ecmul(g1, prvCommit);
for(uint16 i = 0; i < t+1; i++) {
temp = ecOps.ecmul(accused.publicCommitmentsG1[i], complainerIndex**i);
if(i == 0) {
RHS = temp;
}
else {
RHS = ecOps.ecadd(RHS, temp);
}
}
return ecOps.isEqualPoints(LHS, RHS);
}
// A complaint that the accused participant has committed to a non-G1
// curve point.
function complaintNotInG1(uint16 complainerIndex, uint16 accusedIndex, uint16 coefIndex)
checkAuthorizedSender(complainerIndex)
notInPhase(Phase.EndFail)
notInPhase(Phase.EndSuccess)
public
{
Participant storage accused = participants[accusedIndex];
if(accused.isCommitted) {
if(!ecOps.isInG1(accused.publicCommitmentsG1[coefIndex])) {
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
slash(accusedIndex);
}
}
}
// A complaint that the accused participant has committed to a non-G2
// curve point.
function complaintNotInG2(uint16 complainerIndex, uint16 accusedIndex, uint16 coefIndex)
checkAuthorizedSender(complainerIndex)
notInPhase(Phase.EndFail)
notInPhase(Phase.EndSuccess)
public
{
Participant storage accused = participants[accusedIndex];
if(accused.isCommitted) {
if(!ecOps.isInG2(accused.publicCommitmentsG2[coefIndex])) {
curPhase = Phase.EndFail;
emit PhaseChange(Phase.EndFail);
slash(accusedIndex);
}
}
}
// Divides the deposited balance in the contract between
// the enrolled participants except for the participant
// with the slashedIndex. Send slashedIndex = 0 in order
// to divide it between all the participants (no slashing).
function slash(uint16 slashedIndex) private {
uint16 nParticipants = curN;
uint256 amount;
if (slashedIndex == 0) {
amount = address(this).balance/nParticipants;
}
else {
amount = address(this).balance/(nParticipants-1);
}
for (uint16 i = 1; i < (nParticipants+1); i++) {
if (i != slashedIndex) {
require(participants[i].ethPk.send(amount));
}
}
}
// Divides the deposited balance in the contract between
// all the committed paricipants.
function slashUncommitted() private {
uint16 nParticipants = curN;
uint16 committedNum = nParticipants - curNumCommittedLeft;
uint256 amount = address(this).balance/committedNum;
for (uint16 i = 1; i < (nParticipants+1); i++) {
Participant memory part = participants[i];
if (part.isCommitted) {
require(part.ethPk.send(amount));
}
}
}
function decrypt(uint256[2] encrypterPk, uint256 decrypterSk, bytes32 encData)
internal view
returns(bytes32 decryptedData)
{
bytes32 secret = keccak256(abi.encodePacked(ecOps.ecmul(encrypterPk, decrypterSk)));
return encData^secret;
}
////////////////////////////////////////////////////////////////////////////
function getParticipantPkEnc(uint16 participantIndex)
view
external
returns(uint256[2] encPk)
{
return participants[participantIndex].encPk;
}
function getParticipantPubCommitG1(uint16 participantIndex, uint16 coefIndex)
view
external
returns(uint256[2] publicCommitmentsG1)
{
return participants[participantIndex].publicCommitmentsG1[coefIndex];
}
function getParticipantPubCommitG2(uint16 participantIndex, uint16 coefIndex)
view
external
returns(uint256[4] publicCommitmentsG2)
{
return participants[participantIndex].publicCommitmentsG2[coefIndex];
}
function getParticipantPrvCommit(uint16 participantIndex, uint16 committedToIndex)
view
external
returns(uint256 encPrivateCommitments)
{
return participants[participantIndex].encPrivateCommitments[committedToIndex];
}
function getParticipantIsCommitted(uint16 participantIndex)
view
external
returns(bool isCommitted)
{
return participants[participantIndex].isCommitted;
}
}
/**
Test parameters:
n=2
t=1
coefficients:
a0) 54379457673493
a1) 23950433293405
b0) 453845345602931234235
b1) 976507650679506234134
public commitments:
a0)
1368041971066725411361239018179403078339688804905262551154469895335979601856
1618821492510491564023544834479645350362276877645830361512548330678288690656
a1)
2631817276443378672842587294280308402376367224288772184477397977654447923479
10839063031804877909681801875549944362615153185887194276974645822919437293936
b0)
13557179362105442634413454166511695479402464592547795407903173557675549038583
14036788543633373773860064791695546493243519155298095713201690292908488603901
b1)
1410561832783565967033505993299263011778160659525151177822679323808323926727
13048336431799703732972170157397576895462246813007390422018149570212241640252
sks for decryption:
a)9163450 (0x8bd2ba)
b)197435619 (0xbc4a0e3)
corresponding pks:
a)
8010568142108063162131985722241290538226183630284938005062991216917635380726
19057704389966790842586953303181803223520621589676400762135428513026389437262
b)
20560911457302142627844632840089789900964525435158247870992611991075785849245
6050521612570208504883690818928114121824160212045800551636642965355310285042
private commitments:
fa(2)
102280324260303
fb(1)
1430352996282437468369
private commitmente encrypted:
fa(2)
0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf314443cb5d4dece465
fb(1)
0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf7cce6131901dd9c57b
Group PK:
5837875810486042432133468170632608166601746087751836698563291230806091472694,
20890074343725101418521449931290202203738610819454311822513791170653396069990
## Join
["0x11b5d2263b698dd637fb356ea748350b072265cf1acfaf374201f8e99c5bb5f6","0x2a2247476997f4e72285cc8adc57bb0350a105d8f109e523836fc7611d8deb4e"]
["0x2d75104069619e845ea0f055105e3adb22f07fe1206c093880b9fee9942cb99d","0xd60794fcd581fed59e19e802dcc263a5d53f6a04ddebba96a77745474f700f2"]
## Commit
1,
["0x30648c8ef4e8e38d2db668db8a4cab5513343aad935530559090e8a51354fc0",
"0x39438725e6ce47a9b49d4a0b2d90e1cee07d3d7e9a44adb9c0a3cf84078ade0",
"0x5d18e484aeddc886ba162e2fa4bf8bcc125d32230a3fbea6e39ef74de3d6117",
"0x17f6b138a7105622c493ac45d228e9c858544c47227f27a548942c2f01d59970"],
[1,2,3,4,5,6,7,8],
["0x0000000000000000000000000000000000000000000000000000000000000000",
"0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf314443cb5d4dece465"]
2,
["0x1df91772c249f1b2a7e539242ed9eb60e1475f159a376614e91de79c644097f7",
"0x1f088a7004f9c9035af5f4686a5494f576415da8de528c40a67702c5399338fd",
"0x31e598642c78a683eedf66cf7cd4a35a3dd5b5fd8ea947a1c53ab867154fac7",
"0x1cd918c17d9ea92a1a3efb8a999d577d06058a1b205e99769bdc06b6686c8b3c"],
[1,2,3,4,5,6,7,8],
["0x492cb4e02f3d22db552acd7d0d37ac3813a17bb0f62bbf7cce6131901dd9c57b",
"0x0000000000000000000000000000000000000000000000000000000000000000"]
*/ | Returns the group PK. This can only be performed after the DKG has ended. This means only when the current phase is Phase.End . | function getGroupPK()
inPhase(Phase.EndSuccess)
public view returns(uint256[2] groupPK)
{
uint16 nParticipants = n;
groupPK = participants[1].publicCommitmentsG1[0];
for(uint16 i = 2; i <= nParticipants; i++) {
groupPK = ecOps.ecadd(groupPK, participants[i].publicCommitmentsG1[0]);
}
}
| 7,282,313 | [
1,
1356,
326,
1041,
11327,
18,
1220,
848,
1338,
506,
9591,
1839,
326,
31176,
43,
711,
16926,
18,
1220,
4696,
1338,
1347,
326,
783,
6855,
353,
19459,
18,
1638,
263,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11751,
8784,
1435,
7010,
3639,
316,
11406,
12,
11406,
18,
1638,
4510,
13,
203,
3639,
1071,
1476,
1135,
12,
11890,
5034,
63,
22,
65,
1041,
8784,
13,
203,
565,
288,
203,
203,
3639,
2254,
2313,
290,
1988,
27620,
273,
290,
31,
203,
3639,
1041,
8784,
273,
22346,
63,
21,
8009,
482,
5580,
1346,
43,
21,
63,
20,
15533,
203,
377,
203,
3639,
364,
12,
11890,
2313,
277,
273,
576,
31,
277,
1648,
290,
1988,
27620,
31,
277,
27245,
288,
203,
5411,
1041,
8784,
273,
6557,
8132,
18,
557,
1289,
12,
1655,
8784,
16,
22346,
63,
77,
8009,
482,
5580,
1346,
43,
21,
63,
20,
19226,
203,
3639,
289,
203,
565,
289,
203,
203,
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
] |
./full_match/42220/0x97AB3Ea0437Dccfedeb40d223918388943DB2c8f/sources/contracts/ACFI/strategies/ubeswap/StrategyStakingTripleRewardLP.sol | * @dev Event that is fired each time someone harvests the strat./ console.log("stratMgr %s ", stratMgr.vault); setup lp routing setup 2nd output setup 3rd output outputs are not the same | ) public StratManager(stratMgr) {
want = _want;
chef = _chef;
require(_outputToNativeRoute.length >= 2);
output = _outputToNativeRoute[0];
native = _outputToNativeRoute[_outputToNativeRoute.length - 1];
outputToNativeRoute = _outputToNativeRoute;
lpToken0 = IUniswapV2Pair(want).token0();
require(_outputToLp0Route[0] == output);
require(_outputToLp0Route[_outputToLp0Route.length - 1] == lpToken0);
outputToLp0Route = _outputToLp0Route;
lpToken1 = IUniswapV2Pair(want).token1();
require(_outputToLp1Route[0] == output);
require(_outputToLp1Route[_outputToLp1Route.length - 1] == lpToken1);
outputToLp1Route = _outputToLp1Route;
require(_output2ToOutputRoute.length >= 2);
output2 = _output2ToOutputRoute[0];
require(_output2ToOutputRoute[_output2ToOutputRoute.length - 1] == output);
output2ToOutputRoute = _output2ToOutputRoute;
require(_output3ToOutputRoute.length >= 2);
output3 = _output3ToOutputRoute[0];
require(_output3ToOutputRoute[_output3ToOutputRoute.length - 1] == output);
output3ToOutputRoute = _output3ToOutputRoute;
require(output != output2 && output != output3);
_giveAllowances();
}
| 16,323,021 | [
1,
1133,
716,
353,
15950,
1517,
813,
18626,
17895,
90,
25563,
326,
609,
270,
18,
19,
2983,
18,
1330,
2932,
701,
270,
9455,
738,
87,
3104,
609,
270,
9455,
18,
26983,
1769,
3875,
12423,
7502,
3875,
576,
4880,
876,
3875,
890,
13623,
876,
6729,
854,
486,
326,
1967,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
262,
1071,
3978,
270,
1318,
12,
701,
270,
9455,
13,
288,
203,
565,
2545,
273,
389,
17369,
31,
203,
565,
462,
10241,
273,
389,
343,
10241,
31,
203,
565,
2583,
24899,
2844,
774,
9220,
3255,
18,
2469,
1545,
576,
1769,
203,
565,
876,
273,
389,
2844,
774,
9220,
3255,
63,
20,
15533,
203,
565,
6448,
273,
389,
2844,
774,
9220,
3255,
63,
67,
2844,
774,
9220,
3255,
18,
2469,
300,
404,
15533,
203,
565,
876,
774,
9220,
3255,
273,
389,
2844,
774,
9220,
3255,
31,
203,
565,
12423,
1345,
20,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
17369,
2934,
2316,
20,
5621,
203,
565,
2583,
24899,
2844,
774,
48,
84,
20,
3255,
63,
20,
65,
422,
876,
1769,
203,
565,
2583,
24899,
2844,
774,
48,
84,
20,
3255,
63,
67,
2844,
774,
48,
84,
20,
3255,
18,
2469,
300,
404,
65,
422,
12423,
1345,
20,
1769,
203,
565,
876,
774,
48,
84,
20,
3255,
273,
389,
2844,
774,
48,
84,
20,
3255,
31,
203,
565,
12423,
1345,
21,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
17369,
2934,
2316,
21,
5621,
203,
565,
2583,
24899,
2844,
774,
48,
84,
21,
3255,
63,
20,
65,
422,
876,
1769,
203,
565,
2583,
24899,
2844,
774,
48,
84,
21,
3255,
63,
67,
2844,
774,
48,
84,
21,
3255,
18,
2469,
300,
404,
65,
422,
12423,
1345,
21,
1769,
203,
565,
876,
774,
48,
84,
21,
3255,
273,
389,
2844,
774,
48,
84,
21,
3255,
31,
203,
565,
2583,
24899,
2844,
22,
2
] |
pragma solidity ^0.4.24;
// File: contracts/math/SafeMath.sol
/**
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Released under the MIT license.
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/ownership/Ownable.sol
/**
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Released under the MIT license.
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE
*/
/**
* @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;
}
}
// File: contracts/token/ERC20/ERC20Interface.sol
/**
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Released under the MIT license.
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE
*/
/**
* @title
* @dev
*/
contract ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/token/ERC20/ERC20Standard.sol
/**
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Released under the MIT license.
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE
*/
/**
* @title
* @dev
*/
contract ERC20Standard is ERC20Interface {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 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) external 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 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) external 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
*
* To avoid this issue, allowances are only allowed to be changed between zero and non-zero.
*
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) external returns (bool) {
require(allowed[msg.sender][_spender] == 0 || _value == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() external view returns (uint256) {
return totalSupply_;
}
/**
* @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) external view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) external 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) external 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) external 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;
}
}
// File: contracts/token/ERC223/ERC223Interface.sol
/**
* Released under the MIT license.
* https://github.com/Dexaran/ERC223-token-standard/blob/master/LICENSE
*/
contract ERC223Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transfer(address to, uint256 value, bytes data) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts/token/ERC223/ERC223ReceivingContract.sol
/**
* Released under the MIT license.
* https://github.com/Dexaran/ERC223-token-standard/blob/master/LICENSE
*/
/**
* @title Contract that will work with ERC223 tokens.
*/
contract ERC223ReceivingContract {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// File: contracts/token/ERC223/ERC223Standard.sol
/**
* Released under the MIT license.
* https://github.com/Dexaran/ERC223-token-standard/blob/master/LICENSE
*/
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract ERC223Standard is ERC223Interface, ERC20Standard {
using SafeMath for uint256;
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint256 _value, bytes _data) external returns(bool){
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint256 codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint256 _value) external returns(bool){
uint256 codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value);
return true;
}
}
// File: contracts/token/extentions/MintableToken.sol
/**
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Released under the MIT license.
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE
*/
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is ERC223Standard, 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;
}
}
// File: contracts/DAICOVO/TokenController.sol
/// @title A controller that manages permissions to mint specific ERC20/ERC223 token.
/// @author ICOVO AG
/// @dev The target must be a mintable ERC20/ERC223 and also be set its ownership
/// to this controller. It changes permissions in each 3 phases - before the
/// token-sale, during the token-sale and after the token-sale.
///
/// Before the token-sale (State = Init):
/// Only the owner of this contract has a permission to mint tokens.
/// During the token-sale (State = Tokensale):
/// Only the token-sale contract has a permission to mint tokens.
/// After the token-sale (State = Public):
/// Nobody has any permissions. Will be expand in the future:
contract TokenController is Ownable {
using SafeMath for uint256;
MintableToken public targetToken;
address public votingAddr;
address public tokensaleManagerAddr;
State public state;
enum State {
Init,
Tokensale,
Public
}
/// @dev The deployer must change the ownership of the target token to this contract.
/// @param _targetToken : The target token this contract manage the rights to mint.
/// @return
constructor (
MintableToken _targetToken
) public {
targetToken = MintableToken(_targetToken);
state = State.Init;
}
/// @dev Mint and distribute specified amount of tokens to an address.
/// @param to An address that receive the minted tokens.
/// @param amount Amount to mint.
/// @return True if the distribution is successful, revert otherwise.
function mint (address to, uint256 amount) external returns (bool) {
/*
being called from voting contract will be available in the future
ex. if (state == State.Public && msg.sender == votingAddr)
*/
if ((state == State.Init && msg.sender == owner) ||
(state == State.Tokensale && msg.sender == tokensaleManagerAddr)) {
return targetToken.mint(to, amount);
}
revert();
}
/// @dev Change the phase from "Init" to "Tokensale".
/// @param _tokensaleManagerAddr A contract address of token-sale.
/// @return True if the change of the phase is successful, revert otherwise.
function openTokensale (address _tokensaleManagerAddr)
external
onlyOwner
returns (bool)
{
/* check if the owner of the target token is set to this contract */
require(MintableToken(targetToken).owner() == address(this));
require(state == State.Init);
require(_tokensaleManagerAddr != address(0x0));
tokensaleManagerAddr = _tokensaleManagerAddr;
state = State.Tokensale;
return true;
}
/// @dev Change the phase from "Tokensale" to "Public". This function will be
/// cahnged in the future to receive an address of voting contract as an
/// argument in order to handle the result of minting proposal.
/// @return True if the change of the phase is successful, revert otherwise.
function closeTokensale () external returns (bool) {
require(state == State.Tokensale && msg.sender == tokensaleManagerAddr);
state = State.Public;
return true;
}
/// @dev Check if the state is "Init" or not.
/// @return True if the state is "Init", false otherwise.
function isStateInit () external view returns (bool) {
return (state == State.Init);
}
/// @dev Check if the state is "Tokensale" or not.
/// @return True if the state is "Tokensale", false otherwise.
function isStateTokensale () external view returns (bool) {
return (state == State.Tokensale);
}
/// @dev Check if the state is "Public" or not.
/// @return True if the state is "Public", false otherwise.
function isStatePublic () external view returns (bool) {
return (state == State.Public);
}
} | * @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) external view returns (uint256) {
return allowed[_owner][_spender];
}
| 354,681 | [
1,
2083,
358,
866,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
225,
389,
8443,
1758,
1021,
1758,
1492,
29065,
326,
284,
19156,
18,
225,
389,
87,
1302,
264,
1758,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
327,
432,
2254,
5034,
13664,
326,
3844,
434,
2430,
4859,
2319,
364,
326,
17571,
264,
18,
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,
225,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
2935,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// solium-disable security/no-block-members, emit
pragma solidity 0.4.25;
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
import '../tcr/OceanRegistry.sol';
import '../plcrvoting/PLCRVoting.sol';
import '../OceanMarket.sol';
contract OceanDispute is Ownable {
using SafeMath for uint256;
OceanMarket public market;
OceanRegistry public registry;
PLCRVoting public voting;
// complainant is consumer by default
// voting is needed by default => any dispute needs voting to resolve.
struct Dispute {
address complainant; // complainant address
bool resolved; // Indication of if dispute is resolved
uint256 pollID; // identifier for poll
}
// mapping from service id or asset id to Dispute struct
mapping(bytes32 => Dispute) public mDisputes;
// ------
// EVENTS
// ------
event _DisputeInitiated(address indexed _complainant, bytes32 indexed _id, uint256 _pollID);
event _DisputeResolved(address indexed _complainant, bytes32 indexed _id, bool _release, bool _refund);
// ------------
// CONSTRUCTOR:
// ------------
/**
@dev Contructor Sets the addresses
@param _marketAddr Address of the marketplace contract
*/
constructor(address _marketAddr, address _registryAddress, address _plcrAddr) public {
registry = OceanRegistry(_registryAddress);
// get instance of OceanMarket
market = OceanMarket(_marketAddr);
// add dispute resolution contract address to marketplace contract
market.addDisputeAddress();
// add dispute resolution contract address to PLCRVoting contract
voting = PLCRVoting(_plcrAddr);
// get instance of dispute inside PLCRVoting contract
voting.getDisputeInstance(address(this));
}
// --------------------
// Dispute resolution functions
// --------------------
/**
@dev check whether there exists dispute for specific asset or service
@param id identifier associated with the service(i.e., asset Id or service Id)
@return valid Boolean indication of if the dispute exists (true: exists, false: none)
*/
function disputeExist(bytes32 id) public view returns (bool) {
return (mDisputes[id].complainant != address(0));
}
/**
@dev create dispute and submit proofs for specific service agreement
@param id identifier associated with the service agreement (i.e., asset Id or service Id)
@return valid Boolean indication of if the dispute has been initiated
*/
function initiateDispute(bytes32 id) public returns (uint256) {
// pause marketplacce to process payment
market.pausePayment(id);
// create registry challenge for voting if needed; pollID is used for voting
uint256 _pollID = registry.challenge(id, '');
//uint256 _pollID = 0;
// create Dispute struct
mDisputes[id] = Dispute({
complainant : msg.sender,
resolved : false,
pollID : _pollID
});
emit _DisputeInitiated(msg.sender, id, _pollID);
return _pollID;
}
/**
@dev add authorized voter into the poll
@param id identifier associated with the service agreement (i.e., asset Id or service Id)
@param voter address of voter
@return valid Boolean indication of if the dispute has been initiated
*/
function addAuthorizedVoter(bytes32 id, address voter) public onlyOwner() returns (bool) {
uint pollID = mDisputes[id].pollID;
require(voting.pollExists(pollID) == true, 'poll does not exist');
// add authorized voter
voting.addAuthorizedVoter(pollID, voter);
return true;
}
/**
@dev check whether voting of poll ends
@param id identifier associated with the service(i.e., asset Id or service Id)
@return valid Boolean indication of if the voting ends
*/
function votingEnded(bytes32 id) public view returns (bool) {
return registry.challengeCanBeResolved(id);
}
/**
@dev resolve the dispute after the voting ends
@param id identifier associated with the service
@return valid Boolean indication of if the dispute has been resolved
*/
function resolveDispute(bytes32 id) public returns (bool) {
// voting should be ended at this time
if (registry.challengeCanBeResolved(id) == false)
return false;
// resolve challenge in registry
registry.updateStatus(id);
// update status of dispute
mDisputes[id].resolved = true;
bool release = false;
bool refund = false;
// complainant wins the dispute => refund
if (!registry.isWhitelisted(id)) {
refund = true;
// complainant loses the dispute => release payment
} else {
release = true;
}
// resolve the dispute and process payments by passing release and refund flags
market.processPayment(id, release, refund);
emit _DisputeResolved(msg.sender, id, release, refund);
return true;
}
}
| mapping from service id or asset id to Dispute struct | mapping(bytes32 => Dispute) public mDisputes;
| 13,078,314 | [
1,
6770,
628,
1156,
612,
578,
3310,
612,
358,
3035,
2507,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
3890,
1578,
516,
3035,
2507,
13,
1071,
312,
1669,
458,
281,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/libs/math/SafeMath.sol
pragma solidity 0.5.15;
/**
* @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 {
uint constant TEN18 = 10**18;
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/libs/math/Math.sol
pragma solidity 0.5.15;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: contracts/libs/utils/Address.sol
pragma solidity 0.5.15;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: contracts/libs/utils/Arrays.sol
pragma solidity 0.5.15;
/**
* @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;
}
}
}
// File: contracts/libs/utils/ReentrancyGuard.sol
pragma solidity 0.5.15;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: contracts/libs/ownership/Ownable.sol
pragma solidity 0.5.15;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/libs/lifecycle/Pausable.sol
pragma solidity 0.5.15;
/**
* @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 Ownable {
/**
* @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.
*/
constructor () internal {
_paused = true;
}
/**
* @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 owner to pause, triggers stopped state.
*/
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Called by a owner to unpause, returns to normal state.
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/StakingContract.sol
pragma solidity 0.5.15;
contract StakingContract is Pausable, ReentrancyGuard {
using SafeMath for uint256;
using Math for uint256;
using Address for address;
using Arrays for uint256[];
enum Status {Setup, Running, RewardsDisabled}
// EVENTS
event StakeDeposited(address indexed account, uint256 amount);
event WithdrawInitiated(address indexed account, uint256 amount);
event WithdrawExecuted(address indexed account, uint256 amount, uint256 reward);
// STRUCT DECLARATIONS
struct StakeDeposit {
uint256 amount;
uint256 startDate;
uint256 endDate;
uint256 startCheckpointIndex;
uint256 endCheckpointIndex;
bool exists;
}
struct SetupState {
bool staking;
bool rewards;
}
struct StakingLimitConfig {
uint256 maxAmount;
uint256 initialAmount;
uint256 daysInterval;
uint256 maxIntervals;
uint256 unstakingPeriod;
}
struct BaseRewardCheckpoint {
uint256 baseRewardIndex;
uint256 startTimestamp;
uint256 endTimestamp;
uint256 fromBlock;
}
struct BaseReward {
uint256 anualRewardRate;
uint256 lowerBound;
uint256 upperBound;
}
struct RewardConfig {
BaseReward[] baseRewards;
uint256[] upperBounds;
uint256 multiplier; // percent of the base reward applicable
}
// CONTRACT STATE VARIABLES
IERC20 public token;
Status public currentStatus;
SetupState public setupState;
StakingLimitConfig public stakingLimitConfig;
RewardConfig public rewardConfig;
address public rewardsAddress;
uint256 public launchTimestamp;
uint256 public currentTotalStake;
mapping(address => StakeDeposit) private _stakeDeposits;
BaseRewardCheckpoint[] private _baseRewardHistory;
// MODIFIERS
modifier guardMaxStakingLimit(uint256 amount)
{
uint256 resultedStakedAmount = currentTotalStake.add(amount);
uint256 currentStakingLimit = _computeCurrentStakingLimit();
require(resultedStakedAmount <= currentStakingLimit, "[Deposit] Your deposit would exceed the current staking limit");
_;
}
modifier guardForPrematureWithdrawal()
{
uint256 intervalsPassed = _getIntervalsPassed();
require(intervalsPassed >= stakingLimitConfig.maxIntervals, "[Withdraw] Not enough days passed");
_;
}
modifier onlyContract(address account)
{
require(account.isContract(), "[Validation] The address does not contain a contract");
_;
}
modifier onlyDuringSetup()
{
require(currentStatus == Status.Setup, "[Lifecycle] Setup is already done");
_;
}
modifier onlyAfterSetup()
{
require(currentStatus != Status.Setup, "[Lifecycle] Setup is not done");
_;
}
// PUBLIC FUNCTIONS
constructor(address _token, address _rewardsAddress)
onlyContract(_token)
public
{
require(_rewardsAddress != address(0), "[Validation] _rewardsAddress is the zero address");
token = IERC20(_token);
rewardsAddress = _rewardsAddress;
launchTimestamp = now;
currentStatus = Status.Setup;
}
function deposit(uint256 amount)
public
nonReentrant
onlyAfterSetup
whenNotPaused
guardMaxStakingLimit(amount)
{
require(amount > 0, "[Validation] The stake deposit has to be larger than 0");
require(!_stakeDeposits[msg.sender].exists, "[Deposit] You already have a stake");
StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender];
stakeDeposit.amount = stakeDeposit.amount.add(amount);
stakeDeposit.startDate = now;
stakeDeposit.startCheckpointIndex = _baseRewardHistory.length - 1;
stakeDeposit.exists = true;
currentTotalStake = currentTotalStake.add(amount);
_updateBaseRewardHistory();
// Transfer the Tokens to this contract
require(token.transferFrom(msg.sender, address(this), amount), "[Deposit] Something went wrong during the token transfer");
emit StakeDeposited(msg.sender, amount);
}
function initiateWithdrawal()
external
whenNotPaused
onlyAfterSetup
guardForPrematureWithdrawal
{
StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender];
require(stakeDeposit.exists && stakeDeposit.amount != 0, "[Initiate Withdrawal] There is no stake deposit for this account");
require(stakeDeposit.endDate == 0, "[Initiate Withdrawal] You already initiated the withdrawal");
stakeDeposit.endDate = now;
stakeDeposit.endCheckpointIndex = _baseRewardHistory.length - 1;
emit WithdrawInitiated(msg.sender, stakeDeposit.amount);
}
function executeWithdrawal()
external
nonReentrant
whenNotPaused
onlyAfterSetup
{
StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender];
require(stakeDeposit.exists && stakeDeposit.amount != 0, "[Withdraw] There is no stake deposit for this account");
require(stakeDeposit.endDate != 0, "[Withdraw] Withdraw is not initialized");
// validate enough days have passed from initiating the withdrawal
uint256 daysPassed = (now - stakeDeposit.endDate) / 1 days;
require(stakingLimitConfig.unstakingPeriod <= daysPassed, "[Withdraw] The unstaking period did not pass");
uint256 amount = stakeDeposit.amount;
uint256 reward = _computeReward(stakeDeposit);
stakeDeposit.amount = 0;
currentTotalStake = currentTotalStake.sub(amount);
_updateBaseRewardHistory();
require(token.transfer(msg.sender, amount), "[Withdraw] Something went wrong while transferring your initial deposit");
require(token.transferFrom(rewardsAddress, msg.sender, reward), "[Withdraw] Something went wrong while transferring your reward");
emit WithdrawExecuted(msg.sender, amount, reward);
}
function toggleRewards(bool enabled)
external
onlyOwner
onlyAfterSetup
{
Status newStatus = enabled ? Status.Running : Status.RewardsDisabled;
require(currentStatus != newStatus, "[ToggleRewards] This status is already set");
uint256 index;
if (newStatus == Status.RewardsDisabled) {
index = rewardConfig.baseRewards.length - 1;
}
if (newStatus == Status.Running) {
index = _computeCurrentBaseReward();
}
_insertNewCheckpoint(index);
currentStatus = newStatus;
}
// VIEW FUNCTIONS FOR HELPING THE USER AND CLIENT INTERFACE
function currentStakingLimit()
public
onlyAfterSetup
view
returns (uint256)
{
return _computeCurrentStakingLimit();
}
function currentReward(address account)
external
onlyAfterSetup
view
returns (uint256 initialDeposit, uint256 reward)
{
require(_stakeDeposits[account].exists && _stakeDeposits[account].amount != 0, "[Validation] This account doesn't have a stake deposit");
StakeDeposit memory stakeDeposit = _stakeDeposits[account];
stakeDeposit.endDate = now;
return (stakeDeposit.amount, _computeReward(stakeDeposit));
}
function getStakeDeposit()
external
onlyAfterSetup
view
returns (uint256 amount, uint256 startDate, uint256 endDate, uint256 startCheckpointIndex, uint256 endCheckpointIndex)
{
require(_stakeDeposits[msg.sender].exists, "[Validation] This account doesn't have a stake deposit");
StakeDeposit memory s = _stakeDeposits[msg.sender];
return (s.amount, s.startDate, s.endDate, s.startCheckpointIndex, s.endCheckpointIndex);
}
function baseRewardsLength()
external
onlyAfterSetup
view
returns (uint256)
{
return rewardConfig.baseRewards.length;
}
function baseReward(uint256 index)
external
onlyAfterSetup
view
returns (uint256, uint256, uint256)
{
BaseReward memory br = rewardConfig.baseRewards[index];
return (br.anualRewardRate, br.lowerBound, br.upperBound);
}
function baseRewardHistoryLength()
external
view
returns (uint256)
{
return _baseRewardHistory.length;
}
function baseRewardHistory(uint256 index)
external
onlyAfterSetup
view
returns (uint256, uint256, uint256, uint256)
{
BaseRewardCheckpoint memory c = _baseRewardHistory[index];
return (c.baseRewardIndex, c.startTimestamp, c.endTimestamp, c.fromBlock);
}
// OWNER SETUP
function setupStakingLimit(uint256 maxAmount, uint256 initialAmount, uint256 daysInterval, uint256 unstakingPeriod)
external
onlyOwner
whenPaused
onlyDuringSetup
{
require(maxAmount > 0 && initialAmount > 0 && daysInterval > 0 && unstakingPeriod >= 0, "[Validation] Some parameters are 0");
require(maxAmount.mod(initialAmount) == 0, "[Validation] maxAmount should be a multiple of initialAmount");
uint256 maxIntervals = maxAmount.div(initialAmount);
// set the staking limits
stakingLimitConfig.maxAmount = maxAmount;
stakingLimitConfig.initialAmount = initialAmount;
stakingLimitConfig.daysInterval = daysInterval;
stakingLimitConfig.unstakingPeriod = unstakingPeriod;
stakingLimitConfig.maxIntervals = maxIntervals;
setupState.staking = true;
_updateSetupState();
}
function setupRewards(
uint256 multiplier,
uint256[] calldata anualRewardRates,
uint256[] calldata lowerBounds,
uint256[] calldata upperBounds
)
external
onlyOwner
whenPaused
onlyDuringSetup
{
_validateSetupRewardsParameters(multiplier, anualRewardRates, lowerBounds, upperBounds);
// Setup rewards
rewardConfig.multiplier = multiplier;
for (uint256 i = 0; i < anualRewardRates.length; i++) {
_addBaseReward(anualRewardRates[i], lowerBounds[i], upperBounds[i]);
}
uint256 highestUpperBound = upperBounds[upperBounds.length - 1];
// Add the zero annual reward rate
_addBaseReward(0, highestUpperBound, highestUpperBound + 10);
// initiate baseRewardHistory with the first one which should start from 0
_initBaseRewardHistory();
setupState.rewards = true;
_updateSetupState();
}
// INTERNAL
function _updateSetupState()
private
{
if (!setupState.rewards || !setupState.staking) {
return;
}
currentStatus = Status.Running;
}
function _computeCurrentStakingLimit()
private
view
returns (uint256)
{
uint256 intervalsPassed = _getIntervalsPassed();
uint256 baseStakingLimit = stakingLimitConfig.initialAmount;
uint256 intervals = intervalsPassed.min(stakingLimitConfig.maxIntervals - 1);
// initialLimit * ((now - launchMoment) / interval)
return baseStakingLimit.add(baseStakingLimit.mul(intervals));
}
function _getIntervalsPassed()
private
view
returns (uint256)
{
uint256 daysPassed = (now - launchTimestamp) / 1 days;
return daysPassed / stakingLimitConfig.daysInterval;
}
function _computeReward(StakeDeposit memory stakeDeposit)
private
view
returns (uint256)
{
uint256 scale = 10 ** 18;
(uint256 weightedSum, uint256 stakingPeriod) = _computeRewardRatesWeightedSum(stakeDeposit);
if (stakingPeriod == 0) {
return 0;
}
// scaling weightedSum and stakingPeriod because the weightedSum is in the thousands magnitude
// and we risk losing detail while rounding
weightedSum = weightedSum.mul(scale);
uint256 weightedAverage = weightedSum.div(stakingPeriod);
// rewardConfig.multiplier is a percentage expressed in 1/10 (a tenth) of a percent hence we divide by 1000
uint256 accumulator = rewardConfig.multiplier.mul(weightedSum).div(1000);
uint256 effectiveRate = weightedAverage.add(accumulator);
uint256 denominator = scale.mul(36500);
return stakeDeposit.amount.mul(effectiveRate).mul(stakingPeriod).div(denominator);
}
function _computeRewardRatesWeightedSum(StakeDeposit memory stakeDeposit)
private
view
returns (uint256, uint256)
{
uint256 stakingPeriod = (stakeDeposit.endDate - stakeDeposit.startDate) / 1 days;
uint256 weight;
uint256 rate;
// The contract never left the first checkpoint
if (stakeDeposit.startCheckpointIndex == stakeDeposit.endCheckpointIndex) {
rate = _baseRewardFromHistoryIndex(stakeDeposit.startCheckpointIndex).anualRewardRate;
return (rate.mul(stakingPeriod), stakingPeriod);
}
// Computing the first segment base reward
// User could deposit in the middle of the segment so we need to get the segment from which the user deposited
// to the moment the base reward changes
weight = (_baseRewardHistory[stakeDeposit.startCheckpointIndex].endTimestamp - stakeDeposit.startDate) / 1 days;
rate = _baseRewardFromHistoryIndex(stakeDeposit.startCheckpointIndex).anualRewardRate;
uint256 weightedSum = rate.mul(weight);
// Starting from the second checkpoint because the first one is already computed
for (uint256 i = stakeDeposit.startCheckpointIndex + 1; i < stakeDeposit.endCheckpointIndex; i++) {
weight = (_baseRewardHistory[i].endTimestamp - _baseRewardHistory[i].startTimestamp) / 1 days;
rate = _baseRewardFromHistoryIndex(i).anualRewardRate;
weightedSum = weightedSum.add(rate.mul(weight));
}
// Computing the base reward for the last segment
// days between start timestamp of the last checkpoint to the moment he initialized the withdrawal
weight = (stakeDeposit.endDate - _baseRewardHistory[stakeDeposit.endCheckpointIndex].startTimestamp) / 1 days;
rate = _baseRewardFromHistoryIndex(stakeDeposit.endCheckpointIndex).anualRewardRate;
weightedSum = weightedSum.add(weight.mul(rate));
return (weightedSum, stakingPeriod);
}
function _addBaseReward(uint256 anualRewardRate, uint256 lowerBound, uint256 upperBound)
private
{
rewardConfig.baseRewards.push(BaseReward(anualRewardRate, lowerBound, upperBound));
rewardConfig.upperBounds.push(upperBound);
}
function _initBaseRewardHistory()
private
{
require(_baseRewardHistory.length == 0, "[Logical] Base reward history has already been initialized");
_baseRewardHistory.push(BaseRewardCheckpoint(0, now, 0, block.number));
}
function _updateBaseRewardHistory()
private
{
if (currentStatus == Status.RewardsDisabled) {
return;
}
BaseReward memory currentBaseReward = _currentBaseReward();
// Do nothing if currentTotalStake is in the current base reward bounds
if (currentBaseReward.lowerBound <= currentTotalStake && currentTotalStake <= currentBaseReward.upperBound) {
return;
}
uint256 newIndex = _computeCurrentBaseReward();
_insertNewCheckpoint(newIndex);
}
function _insertNewCheckpoint(uint256 newIndex)
private
{
BaseRewardCheckpoint storage oldCheckPoint = _lastBaseRewardCheckpoint();
if (oldCheckPoint.fromBlock < block.number) {
oldCheckPoint.endTimestamp = now;
_baseRewardHistory.push(BaseRewardCheckpoint(newIndex, now, 0, block.number));
} else {
oldCheckPoint.baseRewardIndex = newIndex;
}
}
function _currentBaseReward()
private
view
returns (BaseReward memory)
{
// search for the current base reward from current total staked amount
uint256 currentBaseRewardIndex = _lastBaseRewardCheckpoint().baseRewardIndex;
return rewardConfig.baseRewards[currentBaseRewardIndex];
}
function _baseRewardFromHistoryIndex(uint256 index)
private
view
returns (BaseReward memory)
{
return rewardConfig.baseRewards[_baseRewardHistory[index].baseRewardIndex];
}
function _lastBaseRewardCheckpoint()
private
view
returns (BaseRewardCheckpoint storage)
{
return _baseRewardHistory[_baseRewardHistory.length - 1];
}
function _computeCurrentBaseReward()
private
view
returns (uint256)
{
uint256 index = rewardConfig.upperBounds.findUpperBound(currentTotalStake);
require(index < rewardConfig.upperBounds.length, "[NotFound] The current total staked is out of bounds");
return index;
}
function _validateSetupRewardsParameters
(
uint256 multiplier,
uint256[] memory anualRewardRates,
uint256[] memory lowerBounds,
uint256[] memory upperBounds
)
private
pure
{
require(
anualRewardRates.length > 0 && lowerBounds.length > 0 && upperBounds.length > 0,
"[Validation] All parameters must have at least one element"
);
require(
anualRewardRates.length == lowerBounds.length && lowerBounds.length == upperBounds.length,
"[Validation] All parameters must have the same number of elements"
);
require(lowerBounds[0] == 0, "[Validation] First lower bound should be 0");
require(
(multiplier < 100) && (uint256(100).mod(multiplier) == 0),
"[Validation] Multiplier should be smaller than 100 and divide it equally"
);
}
} | OWNER SETUP set the staking limits | function setupStakingLimit(uint256 maxAmount, uint256 initialAmount, uint256 daysInterval, uint256 unstakingPeriod)
external
onlyOwner
whenPaused
onlyDuringSetup
{
require(maxAmount > 0 && initialAmount > 0 && daysInterval > 0 && unstakingPeriod >= 0, "[Validation] Some parameters are 0");
require(maxAmount.mod(initialAmount) == 0, "[Validation] maxAmount should be a multiple of initialAmount");
uint256 maxIntervals = maxAmount.div(initialAmount);
stakingLimitConfig.maxAmount = maxAmount;
stakingLimitConfig.initialAmount = initialAmount;
stakingLimitConfig.daysInterval = daysInterval;
stakingLimitConfig.unstakingPeriod = unstakingPeriod;
stakingLimitConfig.maxIntervals = maxIntervals;
setupState.staking = true;
_updateSetupState();
}
| 1,846,482 | [
1,
29602,
7855,
3079,
444,
326,
384,
6159,
8181,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3875,
510,
6159,
3039,
12,
11890,
5034,
943,
6275,
16,
2254,
5034,
2172,
6275,
16,
2254,
5034,
4681,
4006,
16,
2254,
5034,
640,
334,
6159,
5027,
13,
203,
565,
3903,
203,
565,
1338,
5541,
203,
565,
1347,
28590,
203,
565,
1338,
26424,
7365,
203,
565,
288,
203,
3639,
2583,
12,
1896,
6275,
405,
374,
597,
2172,
6275,
405,
374,
597,
4681,
4006,
405,
374,
597,
640,
334,
6159,
5027,
1545,
374,
16,
5158,
4354,
65,
10548,
1472,
854,
374,
8863,
203,
3639,
2583,
12,
1896,
6275,
18,
1711,
12,
6769,
6275,
13,
422,
374,
16,
5158,
4354,
65,
943,
6275,
1410,
506,
279,
3229,
434,
2172,
6275,
8863,
203,
203,
3639,
2254,
5034,
943,
24224,
273,
943,
6275,
18,
2892,
12,
6769,
6275,
1769,
203,
3639,
384,
6159,
3039,
809,
18,
1896,
6275,
273,
943,
6275,
31,
203,
3639,
384,
6159,
3039,
809,
18,
6769,
6275,
273,
2172,
6275,
31,
203,
3639,
384,
6159,
3039,
809,
18,
9810,
4006,
273,
4681,
4006,
31,
203,
3639,
384,
6159,
3039,
809,
18,
23412,
6159,
5027,
273,
640,
334,
6159,
5027,
31,
203,
3639,
384,
6159,
3039,
809,
18,
1896,
24224,
273,
943,
24224,
31,
203,
203,
3639,
3875,
1119,
18,
334,
6159,
273,
638,
31,
203,
3639,
389,
2725,
7365,
1119,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "./utils/CitizenNFTTest.sol";
import "../CitizenNFT.sol";
contract NewCityDAOCitizen is CitizenTest {
/// @notice Mint new Citizen NFTs, verify that owners are correct and balance of smart contract
/// is equal to the value transfered for the minting.
string[] hashes;
uint256[] tokenIds;
function testBuyCitizenNFT() public {
payable(address(bob)).transfer(1 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 1);
bob.onlineApplicationForCitizenship(tokenPrice, 1);
assertEq(citizenNFT.balanceOf(address(bob), citizenNFTInternalId), 2);
assertEq(address(citizenNFT).balance, 2 * tokenPrice);
}
/// @notice Output the tokenURI in base64 format to be used in a decoder and observe the json metadata
function testTokenURI() public {
payable(address(bob)).transfer(1 ether);
bob.onlineApplicationForCitizenship(250000000000000000, 1);
string memory meta = citizenNFT.uri(citizenNFTInternalId);
string memory uri = "data:application/json;base64,eyAibmFtZSI6ICJDaXR5REFPIENpdGl6ZW4iLCAiZGVzY3JpcHRpb24iIDogIkEgQ2l0aXplbiBvZiBDaX"
"R5REFPIGhvbGRzIGdvdmVybmFuY2UgaW4gdGhlIG9wZXJhdGlvbnMgYW5kIGFjdGl2aXRpZXMgb2YgQ2l0eURBTy4iLCJpbWFnZSI6ICJpcGZzOi8vUW1S"
"Um51SFZ3aG9ZRUhzVHh6TWNHZHJDZnRoS1RTNjZnbmZVcURaa3Y2a2J6YSJ9";
assertEq(meta, uri);
emit log(meta);
}
function testChangeTokenURI() public {
hashes.push("rekt");
tokenIds.push(citizenNFTInternalId);
odys.changeURIs(hashes, tokenIds);
string memory meta = citizenNFT.uri(citizenNFTInternalId);
string memory uri = "data:application/json;base64,eyAibmFtZSI6ICJDaXR5REFPIENpdGl6ZW4iLCAiZGVzY3JpcHRpb24iIDogIkEgQ2l0aXplbiBvZiBDa"
"XR5REFPIGhvbGRzIGdvdmVybmFuY2UgaW4gdGhlIG9wZXJhdGlvbnMgYW5kIGFjdGl2aXRpZXMgb2YgQ2l0eURBTy4iLCJpbWFnZSI6ICJyZWt0In0=";
assertEq(meta, uri);
emit log(meta);
}
}
contract Legislate is CitizenTest {
/// @notice Test the change of cost for acquiring a citizen NFT.
/// The test is fuzzed, meaning that it will test many different values as arguments
function testOwnerChangeCitizenCost(uint96 _weiAmmount) public {
_weiAmmount = _weiAmmount % 100000000000000000000;
odys.legislateCostOfEntry(_weiAmmount);
payable(address(bob)).transfer(10000 ether);
bob.onlineApplicationForCitizenship(_weiAmmount * 10, 10);
assertEq(citizenNFT.balanceOf(address(bob), citizenNFTInternalId), 10);
assertEq(citizenNFT.inquireCostOfEntry(), _weiAmmount);
}
/// @notice Test the change of the maximum number regular Citizen NFTs that can be minted
/// The test is fuzzed, meaning that it will test many different values as arguments
function testOwnerChangeCitizensNumber(uint96 _housingNumber) public {
odys.buildHousing(_housingNumber);
uint256 housingNumbers = citizenNFT.inquireHousingNumbers();
uint256 mintedNFTs = uint256(_housingNumber) + 10000;
assertEq(mintedNFTs, housingNumbers);
}
/// @notice Test the change of the maximum number of founding Citizen NFTs that can be minted
function testRewriteHistory(uint96 _numberOfNewFoundingCitizens) public {
odys.rewriteHistory(_numberOfNewFoundingCitizens);
assertEq(
citizenNFT.inquireAboutHistory(),
uint256(_numberOfNewFoundingCitizens) + 50
);
}
/// @notice If a non-owner tries to affect the cost of regular Citizen NFTs, it should fail
function testFailnonOwnerChangeCitizenCost(uint96 _weiAmmount) public {
_weiAmmount = _weiAmmount % 100000000000000000000;
bob.legislateCostOfEntry(_weiAmmount);
}
/// @notice If a non-owner user tries to affect the maximum number of regular Citizen NFTs, it should fail
function testFailChangeCitizensNumber(uint256 _housingNumber) public {
bob.buildHousing(_housingNumber);
}
/// @notice The owner should be able to withdraw the funds that exist in the smart contract
function testRaidTheCoffers() public {
payable(address(bob)).transfer(1 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 2);
odys.raidTheCoffers();
assertEq(address(odys).balance, tokenPrice * 2);
}
function testFailtCallInitAgain() public {
odys.initialCitizenship();
}
function testFailReserveCitizenships() public {
odys.reserveCitizenships(1000);
payable(address(bob)).transfer(5000 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 9000);
emit log_uint(
citizenNFT.balanceOf(address(odys), citizenNFTInternalId)
);
}
function testReserveCitizenships() public {
odys.reserveCitizenships(500);
payable(address(bob)).transfer(5000 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 9000);
assertEq(
citizenNFT.balanceOf(address(bob), citizenNFTInternalId),
9000
);
assertEq(
citizenNFT.balanceOf(address(odys), citizenNFTInternalId),
1000
);
}
}
contract Royalties is CitizenTest {
function testDefaultRoyalties() public {
(address receiver, uint256 royalty) = citizenNFT.royaltyInfo(42, 10);
assertEq(receiver, defaultRoyaltyReceiver);
assertEq(royalty, 1);
}
function testTokenRoyalty() public {
odys.setTokenRoyalty(69, address(odys), 3000);
(address receiver, uint256 royalty) = citizenNFT.royaltyInfo(69, 1000);
assertEq(receiver, address(odys));
assertEq(royalty, 300);
}
}
contract Airdrop is CitizenTest {
uint256[] tokenNumbers;
address[] addresses;
function testAirdrop() public {
tokenNumbers = [10, 5];
addresses = [address(bob), address(alice)];
odys.awardCitizenship(addresses, tokenNumbers, 42);
tokenNumbers = [1, 23];
odys.awardCitizenship(addresses, tokenNumbers, 69);
assertEq(citizenNFT.balanceOf(address(bob), 42), 10);
assertEq(citizenNFT.balanceOf(address(alice), 42), 5);
assertEq(citizenNFT.balanceOf(address(bob), 69), 1);
assertEq(citizenNFT.balanceOf(address(alice), 69), 23);
}
function testFailAirdropNotUser() public {
tokenNumbers = [10, 5];
addresses = [address(bob), address(alice)];
bob.awardCitizenship(addresses, tokenNumbers, 42);
}
}
| @notice Mint new Citizen NFTs, verify that owners are correct and balance of smart contract is equal to the value transfered for the minting. | function testBuyCitizenNFT() public {
payable(address(bob)).transfer(1 ether);
uint256 tokenPrice = 250000000000000000;
bob.onlineApplicationForCitizenship(tokenPrice, 1);
bob.onlineApplicationForCitizenship(tokenPrice, 1);
assertEq(citizenNFT.balanceOf(address(bob), citizenNFTInternalId), 2);
assertEq(address(citizenNFT).balance, 2 * tokenPrice);
}
| 6,460,131 | [
1,
49,
474,
394,
385,
305,
452,
275,
423,
4464,
87,
16,
3929,
716,
25937,
854,
3434,
471,
11013,
434,
13706,
6835,
353,
3959,
358,
326,
460,
7412,
329,
364,
326,
312,
474,
310,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1842,
38,
9835,
39,
305,
452,
275,
50,
4464,
1435,
1071,
288,
203,
3639,
8843,
429,
12,
2867,
12,
70,
947,
13,
2934,
13866,
12,
21,
225,
2437,
1769,
203,
3639,
2254,
5034,
1147,
5147,
273,
6969,
12648,
12648,
31,
203,
3639,
800,
70,
18,
21026,
3208,
1290,
39,
305,
452,
275,
3261,
12,
2316,
5147,
16,
404,
1769,
203,
3639,
800,
70,
18,
21026,
3208,
1290,
39,
305,
452,
275,
3261,
12,
2316,
5147,
16,
404,
1769,
203,
3639,
1815,
19508,
12,
71,
305,
452,
275,
50,
4464,
18,
12296,
951,
12,
2867,
12,
70,
947,
3631,
276,
305,
452,
275,
50,
4464,
3061,
548,
3631,
576,
1769,
203,
3639,
1815,
19508,
12,
2867,
12,
71,
305,
452,
275,
50,
4464,
2934,
12296,
16,
576,
380,
1147,
5147,
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
] |
// SPDX-License-Identifier: Unlicense
pragma solidity 0.7.6;
import "SafeMath.sol";
import "IUniswapV3Pool.sol";
import "TickMath.sol";
import "AlphaVault.sol";
import "IStrategy.sol";
/**
* @title Passive Strategy
* @notice Rebalancing strategy for Alpha Vault that maintains the two
* following range orders:
*
* 1. Base order is placed between X - B and X + B + TS.
* 2. Limit order is placed between X - L and X, or between X + TS
* and X + L + TS, depending on which token it holds more of.
*
* where:
*
* X = current tick rounded down to multiple of tick spacing
* TS = tick spacing
* B = base threshold
* L = limit threshold
*
* Note that after these two orders, the vault should have deposited
* all its tokens and should only have a few wei left.
*
* Because the limit order tries to sell whichever token the vault
* holds more of, the vault's holdings will have a tendency to get
* closer to a 1:1 balance. This enables it to continue providing
* liquidity without running out of inventory of either token, and
* achieves this without the need to swap directly on Uniswap and pay
* fees.
*/
contract PassiveStrategy is IStrategy {
using SafeMath for uint256;
AlphaVault public immutable vault;
IUniswapV3Pool public immutable pool;
int24 public immutable tickSpacing;
int24 public baseThreshold;
int24 public limitThreshold;
uint256 public period;
int24 public minTickMove;
int24 public maxTwapDeviation;
uint32 public twapDuration;
address public keeper;
uint256 public lastTimestamp;
int24 public lastTick;
/**
* @param _vault Underlying Alpha Vault
* @param _baseThreshold Used to determine base order range
* @param _limitThreshold Used to determine limit order range
* @param _period Can only rebalance if this length of time has passed
* @param _minTickMove Can only rebalance if price has moved at least this much
* @param _maxTwapDeviation Max deviation from TWAP during rebalance
* @param _twapDuration TWAP duration in seconds for deviation check
* @param _keeper Account that can call `rebalance()`
*/
constructor(
address _vault,
int24 _baseThreshold,
int24 _limitThreshold,
uint256 _period,
int24 _minTickMove,
int24 _maxTwapDeviation,
uint32 _twapDuration,
address _keeper
) {
IUniswapV3Pool _pool = AlphaVault(_vault).pool();
int24 _tickSpacing = _pool.tickSpacing();
vault = AlphaVault(_vault);
pool = _pool;
tickSpacing = _tickSpacing;
baseThreshold = _baseThreshold;
limitThreshold = _limitThreshold;
period = _period;
minTickMove = _minTickMove;
maxTwapDeviation = _maxTwapDeviation;
twapDuration = _twapDuration;
keeper = _keeper;
_checkThreshold(_baseThreshold, _tickSpacing);
_checkThreshold(_limitThreshold, _tickSpacing);
require(_minTickMove >= 0, "minTickMove must be >= 0");
require(_maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0");
require(_twapDuration > 0, "twapDuration must be > 0");
(, lastTick, , , , , ) = _pool.slot0();
}
/**
* @notice Calculates new ranges for orders and calls `vault.rebalance()`
* so that vault can update its positions. Can only be called by keeper.
*/
function rebalance() external override {
require(shouldRebalance(), "cannot rebalance");
(, int24 tick, , , , , ) = pool.slot0();
int24 tickFloor = _floor(tick);
int24 tickCeil = tickFloor + tickSpacing;
vault.rebalance(
0,
0,
tickFloor - baseThreshold,
tickCeil + baseThreshold,
tickFloor - limitThreshold,
tickFloor,
tickCeil,
tickCeil + limitThreshold
);
lastTimestamp = block.timestamp;
lastTick = tick;
}
function shouldRebalance() public view override returns (bool) {
// check called by keeper
if (msg.sender != keeper) {
return false;
}
// check enough time has passed
if (block.timestamp < lastTimestamp.add(period)) {
return false;
}
// check price has moved enough
(, int24 tick, , , , , ) = pool.slot0();
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (tickMove < minTickMove) {
return false;
}
// check price near twap
int24 twap = getTwap();
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation) {
return false;
}
// check price not too close to boundary
int24 maxThreshold = baseThreshold > limitThreshold ? baseThreshold : limitThreshold;
if (
tick < TickMath.MIN_TICK + maxThreshold + tickSpacing ||
tick > TickMath.MAX_TICK - maxThreshold - tickSpacing
) {
return false;
}
return true;
}
/// @dev Fetches time-weighted average price in ticks from Uniswap pool.
function getTwap() public view returns (int24) {
uint32 _twapDuration = twapDuration;
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);
}
/// @dev Rounds tick down towards negative infinity so that it's a multiple
/// of `tickSpacing`.
function _floor(int24 tick) internal view returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
function _checkThreshold(int24 threshold, int24 _tickSpacing) internal pure {
require(threshold > 0, "threshold must be > 0");
require(threshold <= TickMath.MAX_TICK, "threshold too high");
require(threshold % _tickSpacing == 0, "threshold must be multiple of tickSpacing");
}
function setKeeper(address _keeper) external onlyGovernance {
keeper = _keeper;
}
function setBaseThreshold(int24 _baseThreshold) external onlyGovernance {
_checkThreshold(_baseThreshold, tickSpacing);
baseThreshold = _baseThreshold;
}
function setLimitThreshold(int24 _limitThreshold) external onlyGovernance {
_checkThreshold(_limitThreshold, tickSpacing);
limitThreshold = _limitThreshold;
}
function setPeriod(uint256 _period) external onlyGovernance {
period = _period;
}
function setMinTickMove(int24 _minTickMove) external onlyGovernance {
require(_minTickMove >= 0, "minTickMove must be >= 0");
minTickMove = _minTickMove;
}
function setMaxTwapDeviation(int24 _maxTwapDeviation) external onlyGovernance {
require(_maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0");
maxTwapDeviation = _maxTwapDeviation;
}
function setTwapDuration(uint32 _twapDuration) external onlyGovernance {
require(_twapDuration > 0, "twapDuration must be > 0");
twapDuration = _twapDuration;
}
/// @dev Uses same governance as underlying vault.
modifier onlyGovernance {
require(msg.sender == vault.governance(), "governance");
_;
}
}
// 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;
import "IUniswapV3PoolImmutables.sol";
import "IUniswapV3PoolState.sol";
import "IUniswapV3PoolDerivedState.sol";
import "IUniswapV3PoolActions.sol";
import "IUniswapV3PoolOwnerActions.sol";
import "IUniswapV3PoolEvents.sol";
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: 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: Unlicense
pragma solidity 0.7.6;
import "Math.sol";
import "SafeMath.sol";
import "ERC20.sol";
import "IERC20.sol";
import "SafeERC20.sol";
import "ReentrancyGuard.sol";
import "IUniswapV3MintCallback.sol";
import "IUniswapV3SwapCallback.sol";
import "IUniswapV3Pool.sol";
import "TickMath.sol";
import "LiquidityAmounts.sol";
import "PositionKey.sol";
import "IVault.sol";
/**
* @title Alpha Vault
* @notice A vault that provides liquidity on Uniswap V3.
*/
contract AlphaVault is
IVault,
IUniswapV3MintCallback,
IUniswapV3SwapCallback,
ERC20,
ReentrancyGuard
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event CollectFees(
uint256 feesToVault0,
uint256 feesToVault1,
uint256 feesToProtocol0,
uint256 feesToProtocol1
);
event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply);
IUniswapV3Pool public immutable pool;
IERC20 public immutable token0;
IERC20 public immutable token1;
int24 public immutable tickSpacing;
uint256 public protocolFee;
uint256 public maxTotalSupply;
address public strategy;
address public governance;
address public pendingGovernance;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
uint256 public accruedProtocolFees0;
uint256 public accruedProtocolFees1;
/**
* @dev After deploying, strategy needs to be set via `setStrategy()`
* @param _pool Underlying Uniswap V3 pool
* @param _protocolFee Protocol fee expressed as multiple of 1e-6
* @param _maxTotalSupply Cap on total supply
*/
constructor(
address _pool,
uint256 _protocolFee,
uint256 _maxTotalSupply
) ERC20("Alpha Vault", "AV") {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(IUniswapV3Pool(_pool).token0());
token1 = IERC20(IUniswapV3Pool(_pool).token1());
tickSpacing = IUniswapV3Pool(_pool).tickSpacing();
protocolFee = _protocolFee;
maxTotalSupply = _maxTotalSupply;
governance = msg.sender;
require(_protocolFee < 1e6, "protocolFee");
}
/**
* @notice Deposits tokens in proportion to the vault's current holdings.
* @dev These tokens sit in the vault and are not used for liquidity on
* Uniswap until the next rebalance. Also note it's not necessary to check
* if user manipulated price to deposit cheaper, as the value of range
* orders can only by manipulated higher.
* @param amount0Desired Max amount of token0 to deposit
* @param amount1Desired Max amount of token1 to deposit
* @param amount0Min Revert if resulting `amount0` is less than this
* @param amount1Min Revert if resulting `amount1` is less than this
* @param to Recipient of shares
* @return shares Number of shares minted
* @return amount0 Amount of token0 deposited
* @return amount1 Amount of token1 deposited
*/
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
)
external
override
nonReentrant
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Desired > 0 || amount1Desired > 0, "amount0Desired or amount1Desired");
require(to != address(0) && to != address(this), "to");
// Poke positions so vault's current holdings are up-to-date
_poke(baseLower, baseUpper);
_poke(limitLower, limitUpper);
// Calculate amounts proportional to vault's holdings
(shares, amount0, amount1) = _calcSharesAndAmounts(amount0Desired, amount1Desired);
require(shares > 0, "shares");
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
// Pull in tokens from sender
if (amount0 > 0) token0.safeTransferFrom(msg.sender, address(this), amount0);
if (amount1 > 0) token1.safeTransferFrom(msg.sender, address(this), amount1);
// Mint shares to recipient
_mint(to, shares);
emit Deposit(msg.sender, to, shares, amount0, amount1);
require(totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
/// @dev Do zero-burns to poke a position on Uniswap so earned fees are
/// updated. Should be called if total amounts needs to include up-to-date
/// fees.
function _poke(int24 tickLower, int24 tickUpper) internal {
(uint128 liquidity, , , , ) = _position(tickLower, tickUpper);
if (liquidity > 0) {
pool.burn(tickLower, tickUpper, 0);
}
}
/// @dev Calculates the largest possible `amount0` and `amount1` such that
/// they're in the same proportion as total amounts, but not greater than
/// `amount0Desired` and `amount1Desired` respectively.
function _calcSharesAndAmounts(uint256 amount0Desired, uint256 amount1Desired)
internal
view
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
uint256 totalSupply = totalSupply();
(uint256 total0, uint256 total1) = getTotalAmounts();
// If total supply > 0, vault can't be empty
assert(totalSupply == 0 || total0 > 0 || total1 > 0);
if (totalSupply == 0) {
// For first deposit, just use the amounts desired
amount0 = amount0Desired;
amount1 = amount1Desired;
shares = Math.max(amount0, amount1);
} else if (total0 == 0) {
amount1 = amount1Desired;
shares = amount1.mul(totalSupply).div(total1);
} else if (total1 == 0) {
amount0 = amount0Desired;
shares = amount0.mul(totalSupply).div(total0);
} else {
uint256 cross = Math.min(amount0Desired.mul(total1), amount1Desired.mul(total0));
require(cross > 0, "cross");
// Round up amounts
amount0 = cross.sub(1).div(total1).add(1);
amount1 = cross.sub(1).div(total0).add(1);
shares = cross.mul(totalSupply).div(total0).div(total1);
}
}
/**
* @notice Withdraws tokens in proportion to the vault's holdings.
* @param shares Shares burned by sender
* @param amount0Min Revert if resulting `amount0` is smaller than this
* @param amount1Min Revert if resulting `amount1` is smaller than this
* @param to Recipient of tokens
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0) && to != address(this), "to");
uint256 totalSupply = totalSupply();
// Burn shares
_burn(msg.sender, shares);
// Calculate token amounts proportional to unused balances
uint256 unusedAmount0 = getBalance0().mul(shares).div(totalSupply);
uint256 unusedAmount1 = getBalance1().mul(shares).div(totalSupply);
// Withdraw proportion of liquidity from Uniswap pool
(uint256 baseAmount0, uint256 baseAmount1) =
_burnLiquidityShare(baseLower, baseUpper, shares, totalSupply);
(uint256 limitAmount0, uint256 limitAmount1) =
_burnLiquidityShare(limitLower, limitUpper, shares, totalSupply);
// Sum up total amounts owed to recipient
amount0 = unusedAmount0.add(baseAmount0).add(limitAmount0);
amount1 = unusedAmount1.add(baseAmount1).add(limitAmount1);
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
// Push tokens to recipient
if (amount0 > 0) token0.safeTransfer(to, amount0);
if (amount1 > 0) token1.safeTransfer(to, amount1);
emit Withdraw(msg.sender, to, shares, amount0, amount1);
}
/// @dev Withdraws share of liquidity in a range from Uniswap pool.
function _burnLiquidityShare(
int24 tickLower,
int24 tickUpper,
uint256 shares,
uint256 totalSupply
) internal returns (uint256 amount0, uint256 amount1) {
(uint128 totalLiquidity, , , , ) = _position(tickLower, tickUpper);
uint256 liquidity = uint256(totalLiquidity).mul(shares).div(totalSupply);
if (liquidity > 0) {
(uint256 burned0, uint256 burned1, uint256 fees0, uint256 fees1) =
_burnAndCollect(tickLower, tickUpper, _toUint128(liquidity));
// Add share of fees
amount0 = burned0.add(fees0.mul(shares).div(totalSupply));
amount1 = burned1.add(fees1.mul(shares).div(totalSupply));
}
}
/**
* @notice Updates vault's positions. Can only be called by the strategy.
* @dev Two orders are placed - a base order and a limit order. The base
* order is placed first with as much liquidity as possible. This order
* should use up all of one token, leaving only the other one. This excess
* amount is then placed as a single-sided bid or ask order.
*/
function rebalance(
int256 swapAmount,
uint160 sqrtPriceLimitX96,
int24 _baseLower,
int24 _baseUpper,
int24 _bidLower,
int24 _bidUpper,
int24 _askLower,
int24 _askUpper
) external nonReentrant {
require(msg.sender == strategy, "strategy");
_checkRange(_baseLower, _baseUpper);
_checkRange(_bidLower, _bidUpper);
_checkRange(_askLower, _askUpper);
(, int24 tick, , , , , ) = pool.slot0();
require(_bidUpper <= tick, "bidUpper");
require(_askLower > tick, "askLower"); // inequality is strict as tick is rounded down
// Withdraw all current liquidity from Uniswap pool
{
(uint128 baseLiquidity, , , , ) = _position(baseLower, baseUpper);
(uint128 limitLiquidity, , , , ) = _position(limitLower, limitUpper);
_burnAndCollect(baseLower, baseUpper, baseLiquidity);
_burnAndCollect(limitLower, limitUpper, limitLiquidity);
}
// Emit snapshot to record balances and supply
uint256 balance0 = getBalance0();
uint256 balance1 = getBalance1();
emit Snapshot(tick, balance0, balance1, totalSupply());
if (swapAmount != 0) {
pool.swap(
address(this),
swapAmount > 0,
swapAmount > 0 ? swapAmount : -swapAmount,
sqrtPriceLimitX96,
""
);
balance0 = getBalance0();
balance1 = getBalance1();
}
// Place base order on Uniswap
uint128 liquidity = _liquidityForAmounts(_baseLower, _baseUpper, balance0, balance1);
_mintLiquidity(_baseLower, _baseUpper, liquidity);
(baseLower, baseUpper) = (_baseLower, _baseUpper);
balance0 = getBalance0();
balance1 = getBalance1();
// Place bid or ask order on Uniswap depending on which token is left
uint128 bidLiquidity = _liquidityForAmounts(_bidLower, _bidUpper, balance0, balance1);
uint128 askLiquidity = _liquidityForAmounts(_askLower, _askUpper, balance0, balance1);
if (bidLiquidity > askLiquidity) {
_mintLiquidity(_bidLower, _bidUpper, bidLiquidity);
(limitLower, limitUpper) = (_bidLower, _bidUpper);
} else {
_mintLiquidity(_askLower, _askUpper, askLiquidity);
(limitLower, limitUpper) = (_askLower, _askUpper);
}
}
function _checkRange(int24 tickLower, int24 tickUpper) internal view {
int24 _tickSpacing = tickSpacing;
require(tickLower < tickUpper, "tickLower < tickUpper");
require(tickLower >= TickMath.MIN_TICK, "tickLower too low");
require(tickUpper <= TickMath.MAX_TICK, "tickUpper too high");
require(tickLower % _tickSpacing == 0, "tickLower % tickSpacing");
require(tickUpper % _tickSpacing == 0, "tickUpper % tickSpacing");
}
/// @dev Withdraws liquidity from a range and collects all fees in the
/// process.
function _burnAndCollect(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
)
internal
returns (
uint256 burned0,
uint256 burned1,
uint256 feesToVault0,
uint256 feesToVault1
)
{
if (liquidity > 0) {
(burned0, burned1) = pool.burn(tickLower, tickUpper, liquidity);
}
// Collect all owed tokens including earned fees
(uint256 collect0, uint256 collect1) =
pool.collect(
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
feesToVault0 = collect0.sub(burned0);
feesToVault1 = collect1.sub(burned1);
uint256 feesToProtocol0;
uint256 feesToProtocol1;
// Update accrued protocol fees
uint256 _protocolFee = protocolFee;
if (_protocolFee > 0) {
feesToProtocol0 = feesToVault0.mul(_protocolFee).div(1e6);
feesToProtocol1 = feesToVault1.mul(_protocolFee).div(1e6);
feesToVault0 = feesToVault0.sub(feesToProtocol0);
feesToVault1 = feesToVault1.sub(feesToProtocol1);
accruedProtocolFees0 = accruedProtocolFees0.add(feesToProtocol0);
accruedProtocolFees1 = accruedProtocolFees1.add(feesToProtocol1);
}
emit CollectFees(feesToVault0, feesToVault1, feesToProtocol0, feesToProtocol1);
}
/// @dev Deposits liquidity in a range on the Uniswap pool.
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal {
if (liquidity > 0) {
pool.mint(address(this), tickLower, tickUpper, liquidity, "");
}
}
/**
* @notice Calculates the vault's total holdings of token0 and token1 - in
* other words, how much of each token the vault would hold if it withdrew
* all its liquidity from Uniswap.
*/
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(uint256 baseAmount0, uint256 baseAmount1) = getPositionAmounts(baseLower, baseUpper);
(uint256 limitAmount0, uint256 limitAmount1) =
getPositionAmounts(limitLower, limitUpper);
total0 = getBalance0().add(baseAmount0).add(limitAmount0);
total1 = getBalance1().add(baseAmount1).add(limitAmount1);
}
/**
* @notice Amounts of token0 and token1 held in vault's position. Includes
* owed fees but excludes the proportion of fees that will be paid to the
* protocol. Doesn't include fees accrued since last poke.
*/
function getPositionAmounts(int24 tickLower, int24 tickUpper)
public
view
returns (uint256 amount0, uint256 amount1)
{
(uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) =
_position(tickLower, tickUpper);
(amount0, amount1) = _amountsForLiquidity(tickLower, tickUpper, liquidity);
// Subtract protocol fees
uint256 oneMinusFee = uint256(1e6).sub(protocolFee);
amount0 = amount0.add(uint256(tokensOwed0).mul(oneMinusFee).div(1e6));
amount1 = amount1.add(uint256(tokensOwed1).mul(oneMinusFee).div(1e6));
}
/**
* @notice Balance of token0 in vault not used in any position.
*/
function getBalance0() public view returns (uint256) {
return token0.balanceOf(address(this)).sub(accruedProtocolFees0);
}
/**
* @notice Balance of token1 in vault not used in any position.
*/
function getBalance1() public view returns (uint256) {
return token1.balanceOf(address(this)).sub(accruedProtocolFees1);
}
/// @dev Wrapper around `IUniswapV3Pool.positions()`.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128,
uint256,
uint256,
uint128,
uint128
)
{
bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper);
return pool.positions(positionKey);
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @dev Casts uint256 to uint128 with overflow check.
function _toUint128(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta));
if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
/**
* @notice Used to collect accumulated protocol fees.
*/
function collectProtocol(
uint256 amount0,
uint256 amount1,
address to
) external onlyGovernance {
accruedProtocolFees0 = accruedProtocolFees0.sub(amount0);
accruedProtocolFees1 = accruedProtocolFees1.sub(amount1);
if (amount0 > 0) token0.safeTransfer(to, amount0);
if (amount1 > 0) token1.safeTransfer(to, amount1);
}
/**
* @notice Removes tokens accidentally sent to this vault.
*/
function sweep(
IERC20 token,
uint256 amount,
address to
) external onlyGovernance {
require(token != token0 && token != token1, "token");
token.safeTransfer(to, amount);
}
/**
* @notice Used to set the strategy contract that determines the position
* ranges and calls rebalance(). Must be called after this vault is
* deployed.
*/
function setStrategy(address _strategy) external onlyGovernance {
strategy = _strategy;
}
/**
* @notice Used to change the protocol fee charged on pool fees earned from
* Uniswap, expressed as multiple of 1e-6.
*/
function setProtocolFee(uint256 _protocolFee) external onlyGovernance {
require(_protocolFee < 1e6, "protocolFee");
protocolFee = _protocolFee;
}
/**
* @notice Used to change deposit cap for a guarded launch or to ensure
* vault doesn't grow too large relative to the pool. Cap is on total
* supply rather than amounts of token0 and token1 as those amounts
* fluctuate naturally over time.
*/
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyGovernance {
maxTotalSupply = _maxTotalSupply;
}
/**
* @notice Removes liquidity in case of emergency.
*/
function emergencyBurn(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) external onlyGovernance {
pool.burn(tickLower, tickUpper, liquidity);
pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max);
}
/**
* @notice Governance address is not updated until the new governance
* address has called `acceptGovernance()` to accept this responsibility.
*/
function setGovernance(address _governance) external onlyGovernance {
pendingGovernance = _governance;
}
/**
* @notice `setGovernance()` should be called by the existing governance
* address prior to calling this function.
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "pendingGovernance");
governance = msg.sender;
}
modifier onlyGovernance {
require(msg.sender == governance, "governance");
_;
}
}
// 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;
import "Context.sol";
import "IERC20.sol";
import "SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev 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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "IERC20.sol";
import "SafeMath.sol";
import "Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// 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: 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: 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: 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.7.6;
interface IVault {
function deposit(
uint256,
uint256,
uint256,
uint256,
address
)
external
returns (
uint256,
uint256,
uint256
);
function withdraw(
uint256,
uint256,
uint256,
address
) external returns (uint256, uint256);
function getTotalAmounts() external view returns (uint256, uint256);
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.7.6;
interface IStrategy {
function rebalance() external;
function shouldRebalance() external view returns (bool);
} | * @title Passive Strategy @notice Rebalancing strategy for Alpha Vault that maintains the two following range orders: 1. Base order is placed between X - B and X + B + TS. 2. Limit order is placed between X - L and X, or between X + TS and X + L + TS, depending on which token it holds more of. where: X = current tick rounded down to multiple of tick spacing TS = tick spacing B = base threshold L = limit threshold Note that after these two orders, the vault should have deposited all its tokens and should only have a few wei left. Because the limit order tries to sell whichever token the vault holds more of, the vault's holdings will have a tendency to get closer to a 1:1 balance. This enables it to continue providing liquidity without running out of inventory of either token, and achieves this without the need to swap directly on Uniswap and pay fees./ | contract PassiveStrategy is IStrategy {
using SafeMath for uint256;
AlphaVault public immutable vault;
IUniswapV3Pool public immutable pool;
int24 public immutable tickSpacing;
int24 public baseThreshold;
int24 public limitThreshold;
uint256 public period;
int24 public minTickMove;
int24 public maxTwapDeviation;
uint32 public twapDuration;
address public keeper;
uint256 public lastTimestamp;
int24 public lastTick;
constructor(
address _vault,
int24 _baseThreshold,
int24 _limitThreshold,
uint256 _period,
int24 _minTickMove,
int24 _maxTwapDeviation,
uint32 _twapDuration,
address _keeper
) {
IUniswapV3Pool _pool = AlphaVault(_vault).pool();
int24 _tickSpacing = _pool.tickSpacing();
vault = AlphaVault(_vault);
pool = _pool;
tickSpacing = _tickSpacing;
baseThreshold = _baseThreshold;
limitThreshold = _limitThreshold;
period = _period;
minTickMove = _minTickMove;
maxTwapDeviation = _maxTwapDeviation;
twapDuration = _twapDuration;
keeper = _keeper;
_checkThreshold(_baseThreshold, _tickSpacing);
_checkThreshold(_limitThreshold, _tickSpacing);
require(_minTickMove >= 0, "minTickMove must be >= 0");
require(_maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0");
require(_twapDuration > 0, "twapDuration must be > 0");
(, lastTick, , , , , ) = _pool.slot0();
}
function rebalance() external override {
require(shouldRebalance(), "cannot rebalance");
(, int24 tick, , , , , ) = pool.slot0();
int24 tickFloor = _floor(tick);
int24 tickCeil = tickFloor + tickSpacing;
vault.rebalance(
0,
0,
tickFloor - baseThreshold,
tickCeil + baseThreshold,
tickFloor - limitThreshold,
tickFloor,
tickCeil,
tickCeil + limitThreshold
);
lastTimestamp = block.timestamp;
lastTick = tick;
}
function shouldRebalance() public view override returns (bool) {
if (msg.sender != keeper) {
return false;
}
if (block.timestamp < lastTimestamp.add(period)) {
return false;
}
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (tickMove < minTickMove) {
return false;
}
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation) {
return false;
}
if (
tick < TickMath.MIN_TICK + maxThreshold + tickSpacing ||
tick > TickMath.MAX_TICK - maxThreshold - tickSpacing
) {
return false;
}
return true;
}
function shouldRebalance() public view override returns (bool) {
if (msg.sender != keeper) {
return false;
}
if (block.timestamp < lastTimestamp.add(period)) {
return false;
}
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (tickMove < minTickMove) {
return false;
}
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation) {
return false;
}
if (
tick < TickMath.MIN_TICK + maxThreshold + tickSpacing ||
tick > TickMath.MAX_TICK - maxThreshold - tickSpacing
) {
return false;
}
return true;
}
function shouldRebalance() public view override returns (bool) {
if (msg.sender != keeper) {
return false;
}
if (block.timestamp < lastTimestamp.add(period)) {
return false;
}
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (tickMove < minTickMove) {
return false;
}
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation) {
return false;
}
if (
tick < TickMath.MIN_TICK + maxThreshold + tickSpacing ||
tick > TickMath.MAX_TICK - maxThreshold - tickSpacing
) {
return false;
}
return true;
}
(, int24 tick, , , , , ) = pool.slot0();
function shouldRebalance() public view override returns (bool) {
if (msg.sender != keeper) {
return false;
}
if (block.timestamp < lastTimestamp.add(period)) {
return false;
}
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (tickMove < minTickMove) {
return false;
}
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation) {
return false;
}
if (
tick < TickMath.MIN_TICK + maxThreshold + tickSpacing ||
tick > TickMath.MAX_TICK - maxThreshold - tickSpacing
) {
return false;
}
return true;
}
int24 twap = getTwap();
function shouldRebalance() public view override returns (bool) {
if (msg.sender != keeper) {
return false;
}
if (block.timestamp < lastTimestamp.add(period)) {
return false;
}
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (tickMove < minTickMove) {
return false;
}
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation) {
return false;
}
if (
tick < TickMath.MIN_TICK + maxThreshold + tickSpacing ||
tick > TickMath.MAX_TICK - maxThreshold - tickSpacing
) {
return false;
}
return true;
}
int24 maxThreshold = baseThreshold > limitThreshold ? baseThreshold : limitThreshold;
function shouldRebalance() public view override returns (bool) {
if (msg.sender != keeper) {
return false;
}
if (block.timestamp < lastTimestamp.add(period)) {
return false;
}
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
if (tickMove < minTickMove) {
return false;
}
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
if (twapDeviation > maxTwapDeviation) {
return false;
}
if (
tick < TickMath.MIN_TICK + maxThreshold + tickSpacing ||
tick > TickMath.MAX_TICK - maxThreshold - tickSpacing
) {
return false;
}
return true;
}
function getTwap() public view returns (int24) {
uint32 _twapDuration = twapDuration;
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration);
}
function _floor(int24 tick) internal view returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
function _checkThreshold(int24 threshold, int24 _tickSpacing) internal pure {
require(threshold > 0, "threshold must be > 0");
require(threshold <= TickMath.MAX_TICK, "threshold too high");
require(threshold % _tickSpacing == 0, "threshold must be multiple of tickSpacing");
}
function setKeeper(address _keeper) external onlyGovernance {
keeper = _keeper;
}
function setBaseThreshold(int24 _baseThreshold) external onlyGovernance {
_checkThreshold(_baseThreshold, tickSpacing);
baseThreshold = _baseThreshold;
}
function setLimitThreshold(int24 _limitThreshold) external onlyGovernance {
_checkThreshold(_limitThreshold, tickSpacing);
limitThreshold = _limitThreshold;
}
function setPeriod(uint256 _period) external onlyGovernance {
period = _period;
}
function setMinTickMove(int24 _minTickMove) external onlyGovernance {
require(_minTickMove >= 0, "minTickMove must be >= 0");
minTickMove = _minTickMove;
}
function setMaxTwapDeviation(int24 _maxTwapDeviation) external onlyGovernance {
require(_maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0");
maxTwapDeviation = _maxTwapDeviation;
}
function setTwapDuration(uint32 _twapDuration) external onlyGovernance {
require(_twapDuration > 0, "twapDuration must be > 0");
twapDuration = _twapDuration;
}
modifier onlyGovernance {
require(msg.sender == vault.governance(), "governance");
_;
}
}
| 1,743,262 | [
1,
6433,
688,
19736,
282,
868,
28867,
6252,
364,
24277,
17329,
716,
11566,
4167,
326,
2795,
1850,
3751,
1048,
11077,
30,
1850,
404,
18,
3360,
1353,
353,
15235,
3086,
1139,
300,
605,
471,
1139,
397,
605,
397,
15508,
18,
1850,
576,
18,
7214,
1353,
353,
15235,
3086,
1139,
300,
511,
471,
1139,
16,
578,
3086,
1139,
397,
15508,
2398,
471,
1139,
397,
511,
397,
15508,
16,
8353,
603,
1492,
1147,
518,
14798,
1898,
434,
18,
1850,
1625,
30,
2868,
1139,
273,
783,
4024,
16729,
2588,
358,
3229,
434,
4024,
13259,
2868,
15508,
273,
4024,
13259,
2868,
605,
273,
1026,
5573,
2868,
511,
273,
1800,
5573,
1850,
3609,
716,
1839,
4259,
2795,
11077,
16,
326,
9229,
1410,
1240,
443,
1724,
329,
1850,
777,
2097,
2430,
471,
1410,
1338,
1240,
279,
11315,
732,
77,
2002,
18,
1850,
15191,
326,
1800,
1353,
9327,
358,
357,
80,
600,
335,
580,
502,
1147,
326,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
10311,
688,
4525,
353,
467,
4525,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
24277,
12003,
1071,
11732,
9229,
31,
203,
565,
467,
984,
291,
91,
438,
58,
23,
2864,
1071,
11732,
2845,
31,
203,
565,
509,
3247,
1071,
11732,
4024,
18006,
31,
203,
203,
565,
509,
3247,
1071,
1026,
7614,
31,
203,
565,
509,
3247,
1071,
1800,
7614,
31,
203,
565,
2254,
5034,
1071,
3879,
31,
203,
565,
509,
3247,
1071,
1131,
6264,
7607,
31,
203,
565,
509,
3247,
1071,
943,
23539,
438,
758,
13243,
31,
203,
565,
2254,
1578,
1071,
2339,
438,
5326,
31,
203,
565,
1758,
1071,
417,
9868,
31,
203,
203,
565,
2254,
5034,
1071,
1142,
4921,
31,
203,
565,
509,
3247,
1071,
1142,
6264,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
26983,
16,
203,
3639,
509,
3247,
389,
1969,
7614,
16,
203,
3639,
509,
3247,
389,
3595,
7614,
16,
203,
3639,
2254,
5034,
389,
6908,
16,
203,
3639,
509,
3247,
389,
1154,
6264,
7607,
16,
203,
3639,
509,
3247,
389,
1896,
23539,
438,
758,
13243,
16,
203,
3639,
2254,
1578,
389,
11246,
438,
5326,
16,
203,
3639,
1758,
389,
79,
9868,
203,
203,
565,
262,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
23,
2864,
389,
6011,
273,
24277,
12003,
24899,
26983,
2934,
6011,
5621,
203,
3639,
509,
3247,
389,
6470,
18006,
273,
389,
6011,
18,
6470,
18006,
5621,
203,
203,
3639,
9229,
273,
24277,
12003,
24899,
26983,
1769,
203,
3639,
2845,
273,
389,
6011,
31,
203,
3639,
4024,
2
] |
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/test/TestTick.sol | * @dev External wrapper function for Tick.validate()/ | function validate(
uint128 tick,
uint256 minLimit,
uint256 minDurationIndex,
uint256 maxDurationIndex,
uint256 minRateIndex,
uint256 maxRateIndex
) external pure {
return Tick.validate(tick, minLimit, minDurationIndex, maxDurationIndex, minRateIndex, maxRateIndex);
}
| 9,659,405 | [
1,
6841,
4053,
445,
364,
13588,
18,
5662,
1435,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1954,
12,
203,
3639,
2254,
10392,
4024,
16,
203,
3639,
2254,
5034,
1131,
3039,
16,
203,
3639,
2254,
5034,
1131,
5326,
1016,
16,
203,
3639,
2254,
5034,
943,
5326,
1016,
16,
203,
3639,
2254,
5034,
1131,
4727,
1016,
16,
203,
3639,
2254,
5034,
943,
4727,
1016,
203,
565,
262,
3903,
16618,
288,
203,
3639,
327,
13588,
18,
5662,
12,
6470,
16,
1131,
3039,
16,
1131,
5326,
1016,
16,
943,
5326,
1016,
16,
1131,
4727,
1016,
16,
943,
4727,
1016,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-05
*/
pragma solidity ^0.5.0;
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);
}
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 ERC20TOKEN is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
name = "bermudapr"; // CHANGEME, token name ex: Bitcoin
symbol = "brp"; // CHANGEME, token symbol ex: BTC
decimals = 18; // token decimals (ETH=18,USDT=6,BTC=8)
_totalSupply = 18000000000000000000000000000; // total supply including decimals
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;
}
} | total supply including decimals
| _totalSupply = 18000000000000000000000000000; | 7,770,160 | [
1,
4963,
14467,
6508,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
4963,
3088,
1283,
273,
6549,
12648,
12648,
12648,
3784,
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
] |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// 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(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
address[] potentialBearers;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
role.potentialBearers.push(account);
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev remove access to this role for all other accounts
*/
function reset(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
for (uint i = 0; i < role.potentialBearers.length; i++) {
role.bearer[role.potentialBearers[i]] = false;
}
role.potentialBearers.length = 0;
add(role, account);
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
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".
*/
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: openzeppelin-solidity/contracts/access/roles/WhitelistAdminRole.sol
pragma solidity ^0.5.0;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Ownable {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(msg.sender);
}
modifier onlyAdmin() {
require(isWhitelistAdmin(msg.sender) || isOwner(), "Only Whitelist Admin or Owner");
_;
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(msg.sender), "Only Whitelist Admin");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyAdmin {
require(_whitelistAdmins.potentialBearers.length < 20, "Not more than 20 admins are allowed");
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(msg.sender);
}
function transferOwnership(address newOwner) public onlyOwner {
_addWhitelistAdmin(newOwner);
Ownable.transferOwnership(newOwner);
}
function resetWhitelist() public onlyOwner {
_whitelistAdmins.reset(owner());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol
pragma solidity ^0.5.0;
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(msg.sender));
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(msg.sender);
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
**/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: contracts/Token.sol
pragma solidity ^0.5.0;
contract FundamentToken is ERC20Mintable, ERC20Pausable, ERC20Burnable {
string public constant name = "Fundament Token 1";
string public constant symbol = "FND";
uint8 public constant decimals = 0;
}
// File: contracts/ConverterRole.sol
pragma solidity ^0.5.0;
/**
* @title ConverterRole
* @dev Converters are responsible for assigning and removing Whitelisted accounts.
*/
contract ConverterRole is Ownable {
using Roles for Roles.Role;
event ConverterAdded(address indexed account);
event ConverterRemoved(address indexed account);
Roles.Role private _converters;
constructor () internal {
_addConverter(msg.sender);
}
modifier onlyConverterAdmin() {
require(isConverter(msg.sender) || isOwner(), "Only Converter or Owner");
_;
}
modifier onlyConverter() {
require(isConverter(msg.sender), "Only Converter");
_;
}
function isConverter(address account) public view returns (bool) {
return _converters.has(account);
}
function addConverter(address account) public onlyConverterAdmin {
require(_converters.potentialBearers.length < 20, "Not more than 20 admins are allowed");
_addConverter(account);
}
function renounceConverter() public {
_removeConverter(msg.sender);
}
function resetWhitelist() public onlyOwner {
_converters.reset(owner());
}
function _addConverter(address account) internal {
_converters.add(account);
emit ConverterAdded(account);
}
function _removeConverter(address account) internal {
_converters.remove(account);
emit ConverterRemoved(account);
}
}
// File: contracts/Crowdsale.sol
pragma solidity ^0.5.0;
// solium-disable-next-line max-len
/**
* @title Crowdsale
* @dev Crowdsale is an extended verion for fundament from the base crowdsale contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard, WhitelistedRole, ConverterRole {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct Period {
bool converted;
address[] investors;
mapping(address => uint256) balances;
}
Period[] periods;
uint currentPeriodIndex;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _treasury;
// Amount of wei raised
uint256 private _weiRaised;
// Maximum number of allowed investors per period
uint256 _maxInvestors;
/**
* Event for recieving tokens after convertion
* @param investor who comitted the ether
* @param amount token amount obtained from convertion
*/
event Payout (address investor, uint256 amount);
/**
* Event for committing logging
* @param investor who comitted the ether
* @param value weis comitted for purchase
*/
event Committed
(address indexed investor, uint256 value);
/**
* @param treasury Address where collected funds will be forwarded to
* @param token Address of the token being sold
* @param maxInvestors Number of maximum Investors per period
*/
constructor (address payable treasury, IERC20 token, uint256 maxInvestors) public {
require(treasury != address(0));
require(address(token) != address(0));
require(maxInvestors > 0);
periods.push(Period(true, new address[](0)));
periods.push(Period(false, new address[](0)));
currentPeriodIndex = 1;
_treasury = treasury;
_token = token;
_maxInvestors = maxInvestors;
}
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function treasury() public view returns (address payable) {
return _treasury;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
*/
function commit() public nonReentrant payable {
require(msg.value > 0, 'You need to give some money');
address from = msg.sender;
uint256 weiAmount = msg.value;
_preValidatePurchase(from, weiAmount);
if (periods[currentPeriodIndex].balances[from] == 0) {
require(periods[currentPeriodIndex].investors.length < _maxInvestors, 'The limit of investors for this period has been reached.');
periods[currentPeriodIndex].investors.push(from);
}
periods[currentPeriodIndex].balances[from] += weiAmount;
// update state
_weiRaised = _weiRaised.add(weiAmount);
emit Committed(from, weiAmount);
_updatePurchasingState(from, weiAmount);
_forwardFunds();
_postValidatePurchase(from, weiAmount);
}
function committedBalance(address investor) public view returns (uint256 committedAmount) {
uint256 balanceInClosedPeriod = periods[1-currentPeriodIndex].balances[investor];
uint256 balanceInCurrentPeriod = periods[currentPeriodIndex].balances[investor];
if (periods[1-currentPeriodIndex].converted) {
committedAmount = balanceInCurrentPeriod;
} else {
committedAmount = balanceInClosedPeriod + balanceInCurrentPeriod;
}
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param investor Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address investor, uint256 weiAmount) internal view {
require(isWhitelisted(investor));
require(investor != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param investor Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address investor, uint256 weiAmount) internal view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param investor Token purchaser
* @param tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address investor, uint256 tokenAmount) internal {
// Potentially dangerous assumption about the type of the token.
require(ERC20Mintable(address(token())).mint(investor, tokenAmount));
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param investor Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address investor, uint256 tokenAmount) internal {
_deliverTokens(investor, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param investor Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address investor, uint256 weiAmount) internal {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_treasury.transfer(msg.value);
}
function closePeriod() public onlyConverter {
require(periods[1-currentPeriodIndex].converted, 'Please convert old period first.');
periods[1-currentPeriodIndex].converted = false;
currentPeriodIndex = (currentPeriodIndex + 1) % 2;
}
function convert(uint256 rate) public onlyConverter {
require(!periods[1-currentPeriodIndex].converted, 'You already converted');
for (uint i = 0; i < periods[1-currentPeriodIndex].investors.length; i++) {
address investor = periods[1-currentPeriodIndex].investors[i];
uint256 etherBalance = periods[1-currentPeriodIndex].balances[investor];
uint256 tokenAmount = (rate * etherBalance) / 1 ether;
emit Payout(investor, tokenAmount);
_processPurchase(investor, tokenAmount);
periods[1-currentPeriodIndex].balances[investor] = 0;
}
periods[1-currentPeriodIndex].investors.length = 0;
periods[1-currentPeriodIndex].converted = true;
}
function transferOwnership(address newOwner) public onlyOwner {
_addWhitelistAdmin(newOwner);
_addConverter(newOwner);
Ownable.transferOwnership(newOwner);
}
}
| * @return the address where funds are collected./ | function treasury() public view returns (address payable) {
return _treasury;
}
| 1,835,700 | [
1,
2463,
326,
1758,
1625,
284,
19156,
854,
12230,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
9787,
345,
22498,
1435,
1071,
1476,
1135,
261,
2867,
8843,
429,
13,
288,
203,
1377,
327,
389,
27427,
345,
22498,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x97b6a74BcC7Bfc03e9Ce97DE7Fb82a4a03b110Bf/sources/contracts/Pool/Pool.sol | @notice Modifier to check if the pool is not defaulted | modifier nonDefaulted() {
require(defaultedAt == 0, 'PDD');
_;
}
| 16,489,413 | [
1,
9829,
358,
866,
309,
326,
2845,
353,
486,
805,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1661,
1868,
329,
1435,
288,
203,
565,
2583,
12,
1886,
329,
861,
422,
374,
16,
296,
52,
5698,
8284,
203,
565,
389,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-15
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This 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 { }
}
// File: contracts/Laser.sol
pragma solidity 0.6.12;
// Laser with Governance.
contract Laser is ERC20("Laser", "LSR"), Ownable {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "LSR::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "LSR::delegateBySig: invalid nonce");
require(now <= expiry, "LSR::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "LSR::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying LSRs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "LSR::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/LaserStaking.sol
pragma solidity 0.6.12;
contract LaserStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. LSRs to distribute per block.
uint256 lastRewardBlock; // Last block number that LSRs distribution occurs.
uint256 accLaserPerShare; // Accumulated LSRs per share, times 1e12. See below.
}
Laser public laser;
uint256 public laserPerBlock;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
Laser _laser,
uint256 _laserPerBlock,
uint256 _startBlock
) public {
laser = _laser;
laserPerBlock = _laserPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accLaserPerShare: 0
}));
}
// Update the given pool's LSR allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward over the given _from to _to block.
function getLaserReward(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from);
}
// View function to see pending LSRs on frontend.
function pendingLaser(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accLaserPerShare = pool.accLaserPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 reward = getLaserReward(pool.lastRewardBlock, block.number);
uint256 laserReward = reward.mul(laserPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accLaserPerShare = accLaserPerShare.add(laserReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accLaserPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 reward = getLaserReward(pool.lastRewardBlock, block.number);
uint256 laserReward = reward.mul(laserPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
laser.mint(address(this), laserReward);
pool.accLaserPerShare = pool.accLaserPerShare.add(laserReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// When we upgrade to V2 we shall move ownership to a new contract
function updateMaster(address _newContract) public onlyOwner {
laser.transferOwnership(_newContract);
}
// Deposit LP tokens
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accLaserPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeLaserTransfer(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.accLaserPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accLaserPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeLaserTransfer(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.accLaserPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe laser transfer function, just in case if rounding error causes pool to not have enough LSRs.
function safeLaserTransfer(address _to, uint256 _amount) internal {
uint256 laserBal = laser.balanceOf(address(this));
if (laserBal > _amount) {
laser.transfer(_to, _amount);
}
}
} | View function to see pending LSRs on frontend. | function pendingLaser(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accLaserPerShare = pool.accLaserPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 reward = getLaserReward(pool.lastRewardBlock, block.number);
uint256 laserReward = reward.mul(laserPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accLaserPerShare = accLaserPerShare.add(laserReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accLaserPerShare).div(1e12).sub(user.rewardDebt);
}
| 2,262,518 | [
1,
1767,
445,
358,
2621,
4634,
511,
10090,
87,
603,
15442,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4634,
48,
14558,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
48,
14558,
2173,
9535,
273,
2845,
18,
8981,
48,
14558,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2629,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
12423,
3088,
1283,
480,
374,
13,
288,
203,
5411,
2254,
5034,
19890,
273,
9014,
14558,
17631,
1060,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
5411,
2254,
5034,
328,
14558,
17631,
1060,
273,
19890,
18,
16411,
12,
9521,
264,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
5411,
4078,
48,
14558,
2173,
9535,
273,
4078,
48,
14558,
2173,
9535,
18,
1289,
12,
9521,
264,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
289,
203,
3639,
327,
729,
18,
8949,
18,
16411,
12,
8981,
48,
14558,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
///@dev Version of this Oracle Contract is V 1.0
pragma solidity 0.4.24;
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;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to 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;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract Oracle is Ownable {
using SafeMath for uint256;
//Primary Owner
address public ownership;
uint256 public startMarketId;
uint256 public endMarketId;
//Secondary Owner Addresses
mapping (address => bool) private secondaryOwners;
constructor() public {
ownership = msg.sender;
}
/**
* Mappings
*/
// - Mapping of an Asset To their Hourly Prices
// - Maps an assest to hour to price
// - 1 = Forex Price, 2 = Cryptocurrency (BTC) Price
mapping(uint256 => mapping(uint256 => int256)) public AssetToHourToPrice;
// Mapping of price entries to the timestamp when they were set.
// Structure is similar to AssetToHourToPrice but instead of tracking price, it tracks timestamp.
mapping(uint256 => mapping(uint256 => uint256)) public PriceTimestamp;
/**
* EVENTS
*/
event LogPriceUpdate(uint256 _marketId, uint256 _timeslot, int256 _oldValue, int256 _newValue, uint256 _timestamp);
event LogStartMarketIdChange(uint256 _oldValue, uint256 _newValue);
event LogEndMarketIdChange(uint256 _oldValue, uint256 _newValue);
event LogSecondaryOwnerChange(address indexed _owner, bool _state);
event LogFallback(address indexed _caller);
/**
* Modifiers
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
// @dev FIXME security/no-inline-assembly: Avoid using Inline Assembly.
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
//Fallback function
// @dev FIXME this is not exactly a fallaback function and its name collides with the modifier above.
function() isHuman public {
//check if no data is being sent to the contract (malicious code!)
require(msg.data.length == 0);
//Log the fallback function
emit LogFallback(msg.sender);
revert();
}
/**
* Primary ADMIN Functions
*/
// Setter for Price of an Asset. Ex: 0 = Default, 1 = USD/CND, 2 = BTC/USD
function setPrice(uint256 _marketId, uint256 _timeslot, int256 _price) isHuman external {
// Adding Authentication
require(secondaryOwners[msg.sender] == true, "Unauthorised");
// Ensure market ID is in range
require(_marketId != 0 && _marketId >= startMarketId && _marketId <= endMarketId, "marketID outOfRange");
// Ensure prices are 24 hours
require(_timeslot >= 0 && _timeslot <= 23, "timeslot outOfRange");
// Ensure positive price
require(_price > 0 && _price <= 10**18, "price outOfRange");
//Storing the old value to emit in event
int256 value = AssetToHourToPrice[_marketId][_timeslot];
//Update the new price
AssetToHourToPrice[_marketId][_timeslot] = _price;
// Timestamp this entry.
// @dev note that dependence on "now" or "block.timestamp" is mildly concerning. However,
// it is acceptable here as it doesn't determine funds transfer.
// @see https://consensys.github.io/smart-contract-best-practices/recommendations/#timestamp-dependence
uint256 timestamp = now;
PriceTimestamp[_marketId][_timeslot] = timestamp;
//Emit event for price updates
emit LogPriceUpdate(_marketId, _timeslot, value, _price, timestamp);
}
//Setter for Start Market Id
function setStartMarketId(uint256 _startMarketId) isHuman external {
require(secondaryOwners[msg.sender] == true, "Non-secondary user");
require(_startMarketId > 0, "marketID outOfRange");
emit LogStartMarketIdChange(startMarketId, _startMarketId);
startMarketId = _startMarketId;
}
//Setter for End Market Id: ADMIN ONLY
function setEndMarketId(uint256 _endMarketId) isHuman external {
require(secondaryOwners[msg.sender] == true, "Non-secondary user");
require(_endMarketId > 0, "marketID outOfRange");
emit LogEndMarketIdChange(endMarketId, _endMarketId);
endMarketId = _endMarketId;
}
//Getter to be used for the relevant Main Smart Contract
function getPrice(uint256 _marketId, uint256 _timeslot) public view returns ( int256 res ){
// Ensure market ID is in range
require(_marketId != 0 && _marketId >= startMarketId && _marketId <= endMarketId, "marketID outOfRange");
// Ensure prices are 24 hours
require(_timeslot >= 0 && _timeslot <= 23, "timeslot outOfRange");
// Ensure price has been set.
int256 value = AssetToHourToPrice[_marketId][_timeslot];
require(value > 0, "Price Unset");
// Ensure set price is not stale, i.e. not older than 24 hours. This can happen if Oracle daemon has stopped
// updating the contract for some reason.
require(now < ( PriceTimestamp[_marketId][_timeslot].add(1 days)), "Stale Data");
return value;
}
/**
* External Call Functions
*/
/**
* Ownership Functions
*/
//function to add secondary owners
function addOwnerSecondary (address _owner) onlyOwner external {
secondaryOwners[_owner] = true;
emit LogSecondaryOwnerChange(_owner, true);
}
//function to blacklist the secondary owners
function removeOwnerSecondary (address _owner) onlyOwner external {
secondaryOwners[_owner] = false;
emit LogSecondaryOwnerChange(_owner, false);
}
//function to check if an address is an owner
function isSecondaryOwner (address _owner) external view returns (bool res) {
if(secondaryOwners[_owner] == true){
return true;
} else {
return false;
}
}
} | function to blacklist the secondary owners | function removeOwnerSecondary (address _owner) onlyOwner external {
secondaryOwners[_owner] = false;
emit LogSecondaryOwnerChange(_owner, false);
}
| 7,276,729 | [
1,
915,
358,
11709,
326,
9946,
25937,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1206,
5541,
14893,
261,
2867,
389,
8443,
13,
1338,
5541,
3903,
225,
288,
203,
565,
9946,
5460,
414,
63,
67,
8443,
65,
273,
629,
31,
203,
565,
3626,
1827,
14893,
5541,
3043,
24899,
8443,
16,
629,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: hardhat/console.sol
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File: @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol
// 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);
}
}
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.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 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);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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));
}
}
// File: @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract 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;
}
// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 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;
}
// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract 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;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract 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;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface 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);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract 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;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
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 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;
}
// File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal onlyInitializing {
}
function __ERC721URIStorage_init_unchained() internal onlyInitializing {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// File: contracts/SerumNFTs.sol
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721)
// Developed with Love by NFTPunks for SerumNFTS!
pragma solidity ^0.8.4;
library SafeMath {
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;
}
}
}
interface ITransformedNFT {
function mintCollectable(address payable _owner, string memory _tokenURI, string memory _name, address _originalNFTContract,
uint256 _originalNFTId, uint256 _serumId, uint256 _classify) external returns (uint256);
}
contract SerumNFT is
ERC721EnumerableUpgradeable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
ERC721URIStorageUpgradeable
{
using SafeMath for uint256;
// counter for token Ids
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _tokenIds;
CountersUpgradeable.Counter private _collectionIds;
// NFT tokens Mappings
// Mapping from TokenID to TokenMeta data
mapping(uint256 => TokenMeta) private _tokenMeta;
// Mapping from TokenID to CollectionMeta data
mapping(uint256 => CollectionMeta) private _tokenCollection;
// Mapping from TokenID to CardMeta data
mapping(uint256 => CardMeta) private _tokenCard;
// Mapping from collection id to collection meta
mapping(uint256 => CollectionMeta) private _collectionMeta;
// baseURI of token
string private baseURI;
//transformed nft contract
ITransformedNFT private _transformedNftContract;
//trwasury wallet
address private treasuryWallet;
address private adminWallet;
// token metadata structure
struct TokenMeta {
uint256 id;
string name;
address owner;
uint256 price;
uint256 transformationFee;
string fullUri;
string emptyUri;
string description;
string category;
uint256 status; // full = 2 or empty = 1
uint256 classify; // 1 generic , 2 collection , 3 card
address collectionAddress; // to be added incase classify not equal 2 or 3
uint256 cardNum; // to be added incase classify equal 3
}
// collection specific metadata structure
struct CollectionMeta {
address collection_contract;
string collection_name;
}
// card specific metadata structure
struct CardMeta {
address card_contract;
uint card_id;
}
// set the address of the transformed nft contract
function setTransformedContract (address transformedContract_) public onlyOwner{
_transformedNftContract = ITransformedNFT(transformedContract_);
}
//set the treasury wallet
function setTreasuryWallet (address wallet) public onlyOwner {
treasuryWallet = wallet;
}
//set the treasury wallet
function setAdminRole (address to) public onlyOwner {
adminWallet = to;
}
/**
* @dev initializes function is added instead of constructor() in "@openzeppelin/contracts"
*/
function initialize () public initializer {
OwnableUpgradeable.__Ownable_init();
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
ERC721Upgradeable.__ERC721_init(
"Serum NFTs",
"SN"
);
setBaseURI("ipfs://");
}
function setBaseURI(string memory _newBaseURI) public virtual onlyOwner {
baseURI = _newBaseURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* @dev sets token meta
* @param _tokenId uint256 token ID (token number)
* @param _meta TokenMeta
*
* Requirements:
* `tokenId` must exist
* `owner` must the msg.owner
*/
function _setTokenMeta(uint256 _tokenId, TokenMeta memory _meta) private {
require(_exists(_tokenId));
require(ownerOf(_tokenId) == _msgSender() || owner() == _msgSender() || adminWallet == _msgSender());
_tokenMeta[_tokenId] = _meta;
}
/**
* @dev returns tokenId metadata
* @param _tokenId uint256 token ID (token number)
*
* Requirements:
* `tokenId` must exist
*/
function tokenMeta(uint256 _tokenId) public view returns (TokenMeta memory) {
require(_exists(_tokenId));
return _tokenMeta[_tokenId];
}
function getOwner(address add, uint256 id) public view returns (address) {
return IERC721Upgradeable(add).ownerOf(id);
}
/** From the inherited contracs */
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721Upgradeable, ERC721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721URIStorageUpgradeable, ERC721Upgradeable) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721URIStorageUpgradeable, ERC721Upgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
/** end of inherited contracts */
/** Get All Serums*/
function getAllTokens () public view virtual returns (TokenMeta[] memory) {
TokenMeta [] memory allTokens = new TokenMeta[] (_tokenIds.current());
for (uint i = 0; i < _tokenIds.current() ; i++){
allTokens[i] = _tokenMeta[i+1];
}
return allTokens;
}
/** Get serums of owner*/
function getOwnerTokens (address _owner) public view virtual returns (TokenMeta[] memory){
uint numOwnerTokens = ERC721Upgradeable.balanceOf(_owner);
TokenMeta[] memory ownerTokens = new TokenMeta[](numOwnerTokens);
for (uint i = 0; i < numOwnerTokens ; i++){
ownerTokens[i] =_tokenMeta[tokenOfOwnerByIndex(_owner, i)];
}
return ownerTokens;
}
// add new collection
function setCollection (address _collectionAddress, string memory _collectionName) public onlyOwner{
_collectionIds.increment();
uint256 newCollectionId = _collectionIds.current();
CollectionMeta memory _collection = CollectionMeta (_collectionAddress,_collectionName);
_collectionMeta[newCollectionId] = _collection;
}
// get collection name by address
function getAllCollections() public view virtual returns (CollectionMeta[] memory) {
CollectionMeta [] memory allCollections = new CollectionMeta[] (_collectionIds.current());
for (uint i = 0; i < _collectionIds.current() ; i++){
allCollections[i] = _collectionMeta[i+1];
}
return allCollections;
}
/**
* @dev purchase _tokenId
* @param _fullTokenURI string memory tokenURI
* @param _emptyTokenURI string memory empty tokenURI
* @param _name string memory token name
* @param _description string memory for description
* @param _category serum category
* @param _price uint256 token price
* @param _transformationFee fees of applying serum
* @param _classify int for serum type
* Requirements:
* '_price' must be positive
*/
function mintCollectable(
address _owner,
string memory _fullTokenURI,
string memory _emptyTokenURI,
string memory _name,
string memory _description,
string memory _category,
uint256 _price,
uint256 _transformationFee,
uint256 _classify,
address _collectionAddress,
uint256 _cardNum
) public returns (uint256) {
require(_msgSender() == adminWallet || _msgSender() == owner(), 'you are not authorized to add new serum');
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(_owner, newItemId);
_setTokenURI(newItemId, _fullTokenURI);
TokenMeta memory meta = TokenMeta(
newItemId,
_name,
_owner,
_price,
_transformationFee,
_fullTokenURI,
_emptyTokenURI,
_description,
_category,
2, //Full by default at minting
_classify,
_collectionAddress,
_cardNum
);
_setTokenMeta(newItemId, meta);
return newItemId;
}
/** refil serum !! */
function refilSerum(uint256 _serumId) public payable {
require(msg.sender == adminWallet || msg.sender == owner() || msg.sender == ownerOf(_serumId),
'you are not authorized to refil serum');
require(_tokenMeta[_serumId].status == 1, "serum is already full");
uint256 _price = _tokenMeta[_serumId].price;
uint256 _refilFeePercentage = _price.mul(80);
uint256 _refilFees = _refilFeePercentage.div(100);
require(msg.value >= _refilFees, 'insufficient amount');
_tokenMeta[_serumId].status = 2;
_setTokenURI(_serumId, _tokenMeta[_serumId].fullUri);
payable(treasuryWallet).transfer(msg.value); // transfer money to sender
}
/**
* @dev purchase _tokenId
* @param _serumId token ID
* @param _owner address of the owner
* @param _originalNftContract original nft contract
* @param _originalNftId original nft id
* @param _transformedUri URI for the generated nft
* @param _name URI for the generated nft
* Requirements:
* caller must be the owner
*/
function transform(
address payable _owner,
string memory _transformedUri,
string memory _name,
address _originalNftContract,
uint256 _originalNftId,
uint256 _serumId
) public payable returns (uint256) {
// require tokenId to exist, if not code panics
require(_exists(_serumId), "ERC721Metadata: nonexistent token");
// require owner of the tokenId to be the one calling the function,
// if not code panics
require(
ownerOf(_serumId) == _msgSender() || owner() == _msgSender(),
"Ownable: caller is not the owner"
);
// check address of sender
require(msg.sender != address(0) , "Address of sender is not valid");
// check treasury wallet
require(treasuryWallet != address(0) , "Address of receiver is not valid");
// check msg value to be bigger than fee
require(
msg.value >= _tokenMeta[_serumId].transformationFee,
"Please submit the asking price in order to complete the purchase"
);
// require caller to be owner of the orignal nft
require(IERC721Upgradeable(_originalNftContract).ownerOf(_originalNftId) == _msgSender(), "caller is not the owner of original nft");
//require serum to be full (2) (not used)
require(_tokenMeta[_serumId].status == 2, "Serum is already used");
// require the serum to be general or incase of collection specific or card specific to match the collection address and card id
require(
(_tokenMeta[_serumId].classify == 1) ||
(_tokenMeta[_serumId].classify == 2 && _tokenMeta[_serumId].collectionAddress == _originalNftContract) ||
(_tokenMeta[_serumId].classify == 3 && _tokenMeta[_serumId].collectionAddress == _originalNftContract
&& _tokenMeta[_serumId].cardNum == _originalNftId)
, "Serum is not valid for this NFT"
);
/** send MATIC transformation fees to treasury wallet */
payable(treasuryWallet).transfer(msg.value);
/** call the contract to mint */
uint256 TransformedNFTId = _transformedNftContract.mintCollectable(
_owner,
_transformedUri,
_name,
_originalNftContract,
_originalNftId,
_serumId,
_tokenMeta[_serumId].classify
);
//change state of the serum nft incase transaction done successfully
_tokenMeta[_serumId].status = 1;
_setTokenURI(_serumId, _tokenMeta[_serumId].emptyUri); // change token uri
return TransformedNFTId;
}
/**
* @dev purchase new serum
* @param _serumId serum ID
* @param _owner user address
* Requirements:
* existence of serum
*/
function MintUser(address payable _owner, uint256 _serumId)
public payable returns (uint256) {
// check existence of serum and owner of the serum is the deployer
require(_exists(_serumId) && ownerOf(_serumId) == owner(), "Serum not exist");
// check address of sender
require(msg.sender != address(0) , "Address of sender is not valid");
// check treasury wallet
require(treasuryWallet != address(0) , "Address of receiver is not valid");
// check msg value to be bigger than fee
require(
msg.value >= _tokenMeta[_serumId].price,
"Please submit the asking price in order to complete the purchase"
);
/** send MATIC transformation fees to treasury wallet */
payable(treasuryWallet).transfer(msg.value);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(_owner, newItemId);
_setTokenURI(newItemId, _tokenMeta[_serumId].fullUri);
_setTokenMeta(newItemId, _tokenMeta[_serumId]);
_tokenMeta[newItemId].owner = _owner;
_tokenMeta[newItemId].id = newItemId;
return newItemId;
}
} | get collection name by address | function getAllCollections() public view virtual returns (CollectionMeta[] memory) {
CollectionMeta [] memory allCollections = new CollectionMeta[] (_collectionIds.current());
for (uint i = 0; i < _collectionIds.current() ; i++){
allCollections[i] = _collectionMeta[i+1];
}
return allCollections;
}
| 1,592,976 | [
1,
588,
1849,
508,
635,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5514,
15150,
1435,
1071,
1476,
5024,
1135,
261,
2532,
2781,
8526,
3778,
13,
288,
203,
3639,
2200,
2781,
5378,
3778,
777,
15150,
273,
394,
2200,
2781,
8526,
261,
67,
5548,
2673,
18,
2972,
10663,
203,
3639,
364,
261,
11890,
225,
277,
273,
374,
31,
277,
411,
389,
5548,
2673,
18,
2972,
1435,
274,
277,
27245,
95,
203,
5411,
777,
15150,
63,
77,
65,
273,
389,
5548,
2781,
63,
77,
15,
21,
15533,
203,
3639,
289,
203,
3639,
327,
777,
15150,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/**
* @title Smart City Token http://www.smartcitycoin.io
* @dev ERC20 standard compliant / https://github.com/ethereum/EIPs/issues/20 /
* @dev Amount not sold during Crowdsale can be burned by anyone
*/
contract SmartCityToken {
using SafeMath for uint256;
address public owner; // address of Token Owner
address public crowdsale; // address of Crowdsale contract
string constant public standard = "ERC20"; // token standard
string constant public name = "Smart City"; // token name
string constant public symbol = "CITY"; // token symbol
uint256 constant public decimals = 5; // 1 CITY = 100000 tokens
uint256 public totalSupply = 252862966307692; // total token provision; 1 CITY = 0,0001 ETH
uint256 constant public amountForSale = 164360928100000; // amount that might be sold during ICO - 65% of total token supply; 164361 ETH equivalent
uint256 constant public amountReserved = 88502038207692; // amount reserved for founders / loyalty / bounties / etc. - 35% of total token supply
uint256 constant public amountLocked = 61951426745384; // the amount of tokens Owner cannot spend within first 2 years after Crowdsale - 70% of the reserved amount
uint256 public startTime; // Crowdsale end time: from this time on transfer and transferFrom functions are available to anyone except of token Owner
uint256 public unlockOwnerDate; // from this time on transfer and transferFrom functions are available to token Owner
mapping(address => uint256) public balances; // balances array
mapping(address => mapping(address => uint256)) public allowances; // allowances array
bool public burned; // indicates whether excess tokens have already been burned
event Transfer(address indexed from, address indexed to, uint256 value); // Transfer event
event Approval(address indexed _owner, address indexed spender, uint256 value); // Approval event
event Burned(uint256 amount); // Burned event
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @dev Contract initialization
* @param _ownerAddress address Token owner address
* @param _startTime uint256 Crowdsale end time
*
*/
function SmartCityToken(address _ownerAddress, uint256 _startTime) public {
owner = _ownerAddress; // token Owner
startTime = _startTime; // token Start Time
unlockOwnerDate = startTime + 2 years;
balances[owner] = totalSupply; // all tokens are initially allocated to token owner
}
/**
* @dev Transfers token for a specified address
* @param _to address The address to transfer to
* @param _value uint256 The amount to be transferred
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns(bool success) {
require(now >= startTime);
require(_to != address(0));
require(_value <= balances[msg.sender]);
if (msg.sender == owner && now < unlockOwnerDate)
require(balances[msg.sender].sub(_value) >= amountLocked);
balances[msg.sender] = balances[msg.sender].sub(_value); // subtract requested amount from the sender address
balances[_to] = balances[_to].add(_value); // send requested amount to the target address
Transfer(msg.sender, _to, _value); // trigger Transfer event
return true;
}
/**
* @dev Transfers 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) onlyPayloadSize(3 * 32) public returns(bool success) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowances[_from][msg.sender]);
if (now < startTime)
require(_from == owner);
if (_from == owner && now < unlockOwnerDate)
require(balances[_from].sub(_value) >= amountLocked);
uint256 _allowance = allowances[_from][msg.sender];
balances[_from] = balances[_from].sub(_value); // subtract requested amount from the sender address
balances[_to] = balances[_to].add(_value); // send requested amount to the target address
allowances[_from][msg.sender] = _allowance.sub(_value); // reduce sender allowance by transferred amount
Transfer(_from, _to, _value); // trigger Transfer event
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _addr address The address to query the balance of.
* @return uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _addr) public view returns (uint256 balance) {
return balances[_addr];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender address The address which will spend the funds
* @param _value uint256 The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) onlyPayloadSize(2 * 32) public returns(bool success) {
return _approve(_spender, _value);
}
/**
* @dev Workaround for vulnerability described here: https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM
*/
function _approve(address _spender, uint256 _value) internal returns(bool success) {
require((_value == 0) || (allowances[msg.sender][_spender] == 0));
allowances[msg.sender][_spender] = _value; // Set spender allowance
Approval(msg.sender, _spender, _value); // Trigger Approval event
return true;
}
/**
* @dev Burns all the tokens which has not been sold during ICO
*/
function burn() public {
if (!burned && now > startTime) {
uint256 diff = balances[owner].sub(amountReserved); // Get the amount of unsold tokens
balances[owner] = amountReserved;
totalSupply = totalSupply.sub(diff); // Reduce total provision number
burned = true;
Burned(diff); // Trigger Burned event
}
}
/**
* @dev Sets Corwdsale contract address & allowance
* @param _crowdsaleAddress address The address of the Crowdsale contract
*/
function setCrowdsale(address _crowdsaleAddress) public {
require(msg.sender == owner);
require(crowdsale == address(0));
crowdsale = _crowdsaleAddress;
assert(_approve(crowdsale, amountForSale));
}
/**
* @dev Crowdsale contract is allowed to shift token start time to earlier than initially defined date
* @param _newStartTime uint256 New Start Date
*/
function setTokenStart(uint256 _newStartTime) public {
require(msg.sender == crowdsale && _newStartTime < startTime);
startTime = _newStartTime;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* CITY token by www.SmartCityCoin.io
*
* .ossssss: `+sssss`
* ` +ssssss+` `.://++++++//:.` .osssss+
* /sssssssssssssssssssssssss+ssssso`
* -sssssssssssssssssssssssssssss+`
* .+sssssssss+:--....--:/ossssssss+.
* `/ssssssssssso` .sssssssssss/`
* .ossssss+sssssss- :sssss+:ossssso.
* `ossssso. .ossssss: `/sssss/ `/ssssss.
* ossssso` `+ssssss+` .osssss: /ssssss`
* :ssssss` /sssssso:ssssso. +o+/:-`
* osssss+ -sssssssssss+`
* ssssss: .ossssssss/
* osssss/ `+ssssss-
* /ssssso :ssssss
* .ssssss- :ssssss
* :ssssss- :ssssss `
* /ssssss/` :ssssss `/s+:`
* :sssssso:. :ssssss ./ssssss+`
* .+ssssssso/-.`:ssssss``.-/osssssss+.
* .+ssssssssssssssssssssssssssss+-
* `:+ssssssssssssssssssssss+:`
* `.:+osssssssssssso+:.`
* `/ssssss.`
* :ssssss
*/ | * @dev Sets Corwdsale contract address & allowance @param _crowdsaleAddress address The address of the Crowdsale contract/ | function setCrowdsale(address _crowdsaleAddress) public {
require(msg.sender == owner);
require(crowdsale == address(0));
crowdsale = _crowdsaleAddress;
assert(_approve(crowdsale, amountForSale));
}
| 1,043,841 | [
1,
2785,
9557,
91,
2377,
5349,
6835,
1758,
473,
1699,
1359,
282,
389,
71,
492,
2377,
5349,
1887,
1758,
1021,
1758,
434,
326,
385,
492,
2377,
5349,
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
] | [
1,
1,
1,
1,
1,
1,
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,
11440,
492,
2377,
5349,
12,
2867,
389,
71,
492,
2377,
5349,
1887,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
3639,
2583,
12,
71,
492,
2377,
5349,
422,
1758,
12,
20,
10019,
203,
203,
3639,
276,
492,
2377,
5349,
273,
389,
71,
492,
2377,
5349,
1887,
31,
203,
3639,
1815,
24899,
12908,
537,
12,
71,
492,
2377,
5349,
16,
3844,
1290,
30746,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
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);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev 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;
}
}
/**
* @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;
}
}
contract TimeUtil {
uint256 private constant blockPerSecNumerator = 1;
uint256 private constant blockPerSecDenominator = 13;
using SafeMath for uint256;
function blocksFromCurrent(uint256 targetTime) public view returns (uint256) {
return toBlocks(targetTime.sub(block.timestamp));
}
function blocksFromBegin(uint256 targetTime) public view returns (uint256) {
return blocksFromCurrent(targetTime).add(block.number);
}
function toBlocks(uint256 diffTime) public pure returns (uint256) {
return diffTime.mul(blockPerSecNumerator).div(blockPerSecDenominator);
}
}
/**
* @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);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev 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));
}
}
/**
* @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;
}
}
abstract contract AdminAccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet private _adminSet;
constructor() internal {
_adminSet.add(_msgSender());
}
function getAdministrators() public view returns (address[] memory addresses) {
addresses = new address[](_adminSet.length());
for (uint256 index = 0; index < addresses.length; ++index) addresses[index] = _adminSet.at(index);
}
function addAdministrator(address account) public onlyAdmin {
require(_adminSet.add(account), "AccessControl: account already an administrator.");
}
function clearAdministrator(address account) public onlyAdmin {
require(_adminSet.length() > 1, "AccessControl: cannot remove last administrator.");
require(_adminSet.remove(account), "AccessControl: account not an administrator.");
}
modifier onlyAdmin() {
require(_adminSet.contains(_msgSender()), "AccessControl: require administrator account");
_;
}
}
contract StakingBase is ReentrancyGuard, AdminAccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount; // deposited amount
uint256 rewardDebt; // reward debt for pending calculation
uint256 exChanged; // total claimed token
}
// Info of each pool.
struct PoolInfo {
address tokenAddress; // address of sataking token
uint256 poolPledged; // total pledged token per pool
uint256 allocPoint; // How many allocation points assigned to this pool.
uint256 lastRewardBlock; // Last block number that token distribution occurs.
uint256 accTokenPerShare; // Accumulated token per share, times 1e12.
}
struct PeriodeReleases {
uint256 blockOffset; // number of block from mining begin
uint256 tokenPerBlock; // number of tokens release per block
}
// How many allocation points assigned in total.
uint256 public totalAllocPoint;
// periodes
PeriodeReleases[] public periodes;
// Tokens that will be released
uint256 public miningTotal;
// the beginning block of mining
uint256 public miningBeginBlock;
// yao token
IERC20 private _yao;
bool public isEmergency;
// abstraction pools, which might be an ERC1155 pool, an ERC20 pool, even a CFX pool
// depens on inherition
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
event Withdraw(address indexed user, uint256 indexed pId, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pId, uint256 amount);
constructor(IERC20 yao_) public {
_yao = yao_;
isEmergency = false;
}
function setEmergency(bool isEmergency_) public onlyAdmin {
isEmergency = isEmergency_;
}
/**
* @dev add new pool, with alloc point
* any inherited contract should call this function to create the pool
*/
function _add(uint256 _allocPoint, address tokenAddress) internal onlyAdmin returns (uint256) {
_updateAllPools();
uint256 pid = poolInfo.length;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({tokenAddress: tokenAddress, poolPledged: 0, allocPoint: _allocPoint, lastRewardBlock: miningBeginBlock, accTokenPerShare: 0}));
return pid;
}
/**
* @dev modify an pool's alloc point.
* in order to minimize inaccuracy, it should call before the pool opens or as soon as a periode is advanced
*/
function setAllocPoint(uint256 pId, uint256 _allocPoint) public virtual onlyAdmin {
_updateAllPools();
PoolInfo storage pool = poolInfo[pId];
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
pool.allocPoint = _allocPoint;
}
/**
* @dev get the balance of owner's periode token
*/
function pendingToken(uint256 pId, address _user) external view returns (uint256) {
PoolInfo memory pool = poolInfo[pId];
UserInfo memory user = userInfo[pId][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
if (block.number > pool.lastRewardBlock && pool.poolPledged > 0) {
uint256 yaoReward = getPoolReward(pool.lastRewardBlock, pool.allocPoint);
accTokenPerShare = accTokenPerShare.add(yaoReward.mul(1e12).div(pool.poolPledged));
}
return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt);
}
/**
* @dev refresh all pool infomation, should be called before modification is maked for any pools
*/
function _updateAllPools() internal virtual {
for (uint256 idxPool = 0; idxPool < poolInfo.length; ++idxPool) _updatePool(poolInfo[idxPool]);
}
/**
* @dev Update reward variables of the given pool to be up-to-date.
*/
function _updatePool(PoolInfo storage pool) internal virtual {
// if the mining is not started there is no needs to update
if (block.number <= pool.lastRewardBlock) {
return;
}
// if there is nothing in this pool
if (pool.poolPledged == 0) {
pool.lastRewardBlock = block.number;
return;
}
// get reward
uint256 yaoReward = getPoolReward(pool.lastRewardBlock, pool.allocPoint);
// calcult accumulate token per share
pool.accTokenPerShare = pool.accTokenPerShare.add(yaoReward.mul(1e12).div(pool.poolPledged));
// update pool last reward block
pool.lastRewardBlock = block.number;
}
/**
* @dev deposit token into pool
* any inherited contract should call this function to make a deposit
*/
function _deposit(uint256 pId, uint256 _amount) internal nonReentrant returns (uint256) {
PoolInfo storage pool = poolInfo[pId];
UserInfo storage user = userInfo[pId][_msgSender()];
_withdrawPool(pId, user);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
pool.poolPledged = pool.poolPledged.add(_amount);
return user.amount;
}
/**
* @dev withdraw staking token from pool
* any inherited contract should call this function to make a withdraw
*/
function _withdraw(uint256 pId, uint256 _amount) internal nonReentrant returns (uint256) {
PoolInfo storage pool = poolInfo[pId];
UserInfo storage user = userInfo[pId][_msgSender()];
require(user.amount >= _amount, "StakingBase: _withdraw needs amount > user.amount");
_withdrawPool(pId, user);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
pool.poolPledged = pool.poolPledged.sub(_amount);
return user.amount;
}
/**
* @dev withdraw without tokens, emergency only
* any inherited contract should call this function to make a emergencyWithdraw
*/
function _emergencyWithdraw(uint256 pId) internal nonReentrant onEmergency returns (uint256) {
PoolInfo storage pool = poolInfo[pId];
UserInfo storage user = userInfo[pId][_msgSender()];
if (user.amount > 0) {
user.amount = 0;
user.rewardDebt = 0;
pool.poolPledged = pool.poolPledged.sub(user.amount);
}
}
/**
* @dev withdraw periode token from pool(in this case is Yao)
*/
function withdrawPool(uint256 pId) public nonReentrant {
_withdrawPool(pId, userInfo[pId][_msgSender()]);
}
/**
* @dev withdraw periode token from every pool(in this case is Yao)
*/
function withdrawPoolAll() public nonReentrant {
for (uint256 index = 0; index < poolInfo.length; ++index) {
UserInfo storage user = userInfo[index][_msgSender()];
if (user.amount > 0) _withdrawPool(index, user);
}
}
/**
* @dev implemtation of withdraw pending tokens
*/
function _withdrawPool(uint256 pId, UserInfo storage user) private {
PoolInfo storage pool = poolInfo[pId];
// update pool for new accTokenPerShare
_updatePool(pool);
// calculate pending tokens
uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);
// if has pending token, then send
if (pending > 0) {
safeTransferYAO(_msgSender(), pending);
user.exChanged = user.exChanged.add(pending);
emit Withdraw(_msgSender(), pId, pending);
}
// update user reward debut
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
}
// Safe Yao transfer function, just in case if rounding error causes pool to not have enough tokens.
function safeTransferYAO(address to, uint256 amount) internal {
if (amount > 0) {
uint256 acgBal = _yao.balanceOf(address(this));
if (amount > acgBal) {
_yao.transfer(to, acgBal);
} else {
_yao.transfer(to, amount);
}
}
}
/**
* @dev get pool reward
*/
function getPoolReward(uint256 _poolLastRewardBlock, uint256 _poolAllocPoint) internal view returns (uint256) {
return getPoolReward(_poolLastRewardBlock, _poolAllocPoint, block.number);
}
/**
* @dev get pool reward
*/
function getPoolReward(
uint256 _poolLastRewardBlock,
uint256 _poolAllocPoint,
uint256 _blockNumber
) internal view returns (uint256) {
if (_blockNumber < miningBeginBlock) return 0;
// get offset of current block from beginning
uint256 currentOffset = _blockNumber.sub(miningBeginBlock);
// get offset of last reward block from beginning
uint256 lasRewardBlockOffset = _poolLastRewardBlock.sub(miningBeginBlock);
uint256 poolRewards = 0;
// from last periode to first periode
for (uint256 idx = periodes.length - 1; ; --idx) {
// if last reward is later that current periode,
// so we sure that lasRewardBlockOffset to currentOffset is in the same periode,
// accumulate rewards then stop iterate.
// if not, that lasRewardBlockOffset and currentOffset is in the different periode,
// accumulate rewards and move currentOffset to the beginning of current periode, contiune to iterate
PeriodeReleases memory onePeriode = periodes[idx];
if (lasRewardBlockOffset >= onePeriode.blockOffset) {
poolRewards = poolRewards.add(onePeriode.tokenPerBlock * currentOffset.sub(lasRewardBlockOffset));
break;
} else if (currentOffset > onePeriode.blockOffset) {
poolRewards = poolRewards.add(onePeriode.tokenPerBlock * (currentOffset.sub(onePeriode.blockOffset)));
currentOffset = onePeriode.blockOffset;
}
}
// apply allocation percentage to pool reward
return poolRewards.mul(_poolAllocPoint).div(totalAllocPoint);
}
function getBlockInfo() public view returns (uint256, uint256) {
return (block.timestamp, block.number);
}
function estimateRewards(
uint256 pId,
uint256 amount,
uint256 blockOffset
) public view returns (uint256 rewards) {
PoolInfo memory pool = poolInfo[pId];
uint256 yaoReward = getPoolReward(block.number, pool.allocPoint, block.number.add(blockOffset));
return yaoReward.mul(amount).div(pool.poolPledged.add(amount));
}
function totalReleased() public view returns (uint256) {
if (block.number < miningBeginBlock) return 0;
// get offset of current block from beginning
uint256 currentOffset = block.number.sub(miningBeginBlock);
uint256 sum = 0;
for (uint256 idx = periodes.length - 1; ; --idx) {
PeriodeReleases memory onePeriode = periodes[idx];
if (currentOffset > onePeriode.blockOffset) {
sum = sum.add(onePeriode.tokenPerBlock * (currentOffset.sub(onePeriode.blockOffset)));
currentOffset = onePeriode.blockOffset;
if (idx == 0) break;
}
}
return sum;
}
modifier onEmergency() {
require(isEmergency, "StakingBase: not in emergency");
_;
}
}
/**
* @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;
}
/**
* _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.
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. 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 Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
constructor() internal {
_registerInterface(
ERC1155Receiver(address(0)).onERC1155Received.selector ^
ERC1155Receiver(address(0)).onERC1155BatchReceived.selector
);
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToUintMap;
*
* // Declare a set state variable
* EnumerableMap.UintToUintMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> uint256` (`UintToUintMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256Touint256Map) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToUintMap
struct UintToUintMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToUintMap storage map,
uint256 key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToUintMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToUintMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(key)));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToUintMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(key), errorMessage));
}
}
contract StakingERC1155Receiver is ERC1155Receiver {
event OnERC1155Received(address operator, address from, uint256 id, uint256 value, bytes data);
event OnERC1155BatchReceived(address operator, address from, uint256[] ids, uint256[] values, bytes data);
/**
@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.
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
) public virtual override returns (bytes4) {
//return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
emit OnERC1155Received(operator, from, id, value, data);
return this.onERC1155Received.selector;
}
/**
@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. 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
) public virtual override returns (bytes4) {
//return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));
emit OnERC1155BatchReceived(operator, from, ids, values, data);
return this.onERC1155BatchReceived.selector;
}
}
abstract contract StakingERC1155 is StakingBase, StakingERC1155Receiver {
using SafeMath for uint256;
using EnumerableMap for EnumerableMap.UintToUintMap;
using EnumerableSet for EnumerableSet.UintSet;
uint256 constant ERC1155StakingMax = 5;
mapping(uint256 => mapping(address => EnumerableMap.UintToUintMap)) private _erc1155Pools;
EnumerableSet.UintSet private _erc1155PoolIdSet;
event DepositERC1155(address indexed user, uint256 indexed pid, uint256[] erc1155Id, uint256[] amount);
event WithdrawERC1155(address indexed user, uint256 indexed pid, uint256[] erc1155Id, uint256[] amount);
constructor() internal {}
/**
* @dev add a erc1155 pool
*/
function addERC1155Pool(uint256 _allocPoint, address _1155TokenAddr) public onlyAdmin {
uint256 pId = _add(_allocPoint, _1155TokenAddr);
_erc1155PoolIdSet.add(pId);
}
/**
* @dev deposit erc1155 token to pool
*/
function depositERC1155(
uint256 pId,
uint256[] calldata erc1155Ids,
uint256[] calldata amounts
) public validAsERC1155PId(pId) {
require(erc1155Ids.length == amounts.length, "StakingERC1155: _ids and amounts length mismatch");
uint256 amountSum = 0;
EnumerableMap.UintToUintMap storage erc1155Entities = _erc1155Pools[pId][_msgSender()];
for (uint256 index = 0; index < erc1155Ids.length; ++index) {
(, uint256 count) = erc1155Entities.tryGet(erc1155Ids[index]);
erc1155Entities.set(erc1155Ids[index], count.add(amounts[index]));
amountSum = amountSum.add(amounts[index]);
}
require(_deposit(pId, amountSum) <= ERC1155StakingMax, "StakingERC1155: NFT staking count exceed its maximun");
IERC1155 tokenProdiver = IERC1155(poolInfo[pId].tokenAddress); // get token provider by id
tokenProdiver.safeBatchTransferFrom(_msgSender(), address(this), erc1155Ids, amounts, "");
emit DepositERC1155(_msgSender(), pId, erc1155Ids, amounts);
}
/**
* @dev withdraw erc1155 token from pool
*/
function withdrawERC1155(
uint256 pId,
uint256[] calldata erc1155Ids,
uint256[] calldata amounts
) public validAsERC1155PId(pId) {
require(erc1155Ids.length == amounts.length, "StakingERC1155: _ids and amounts length mismatch");
uint256 amountSum = 0;
EnumerableMap.UintToUintMap storage erc1155Entities = _erc1155Pools[pId][_msgSender()];
for (uint256 index = 0; index < erc1155Ids.length; ++index) {
uint256 id = erc1155Ids[index];
uint256 amount = amounts[index];
uint256 count = erc1155Entities.get(id);
uint256 rest = count.sub(amount);
if (rest > 0) erc1155Entities.set(id, rest);
else erc1155Entities.remove(id);
amountSum = amountSum.add(amount);
}
_withdraw(pId, amountSum);
IERC1155 tokenProdiver = IERC1155(poolInfo[pId].tokenAddress); // get token provider by id
tokenProdiver.safeBatchTransferFrom(address(this), _msgSender(), erc1155Ids, amounts, "");
emit WithdrawERC1155(_msgSender(), pId, erc1155Ids, amounts);
}
/**
* @dev withdraw all staked erc1155 tokens in emergency, without tansfer pending tokens
*/
function emergencyWithdrawERC1155(uint256 pId) public onEmergency validAsERC1155PId(pId) {
(uint256[] memory erc1155Ids, uint256[] memory amounts) = pledgedERC1155(pId, _msgSender());
_emergencyWithdraw(pId);
IERC1155 tokenProdiver = IERC1155(poolInfo[pId].tokenAddress); // get token provider by id
tokenProdiver.safeBatchTransferFrom(address(this), _msgSender(), erc1155Ids, amounts, "");
}
/**
* @dev get user pledgedERC1155 tokens for all pools
*/
function pledgedERC1155(uint256 pId, address user) public view validAsERC1155PId(pId) returns (uint256[] memory erc1155Ids, uint256[] memory amounts) {
EnumerableMap.UintToUintMap storage erc1155Entities = _erc1155Pools[pId][user];
uint256 count = erc1155Entities.length();
erc1155Ids = new uint256[](count);
amounts = new uint256[](count);
for (uint256 index = 0; index < count; ++index) (erc1155Ids[index], amounts[index]) = erc1155Entities.at(index);
}
/**
* @dev get all ERC1155 token pool ids
*/
function listERC1155PoolIds() public view returns (uint256[] memory poolIds) {
poolIds = new uint256[](_erc1155PoolIdSet.length());
for (uint256 index = 0; index < poolIds.length; ++index) poolIds[index] = _erc1155PoolIdSet.at(index);
}
/**
* @dev valid a pool id is belonged to erc 20 pool
*/
modifier validAsERC1155PId(uint256 pId) {
require(_erc1155PoolIdSet.contains(pId), "StakingERC1155: pool id not belong to defi ERC1155");
_;
}
}
/**
* @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);
}
/**
* @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 StakingERC721Receiver is ERC165, IERC721Receiver {
constructor() internal {
_registerInterface(StakingERC721Receiver(address(0)).onERC721Received.selector);
}
/**
* @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;
}
}
abstract contract StakingERC721 is StakingBase, StakingERC721Receiver {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.UintSet;
uint256 constant ERC721StakingMax = 5;
mapping(uint256 => mapping(address => EnumerableSet.UintSet)) private erc721Pools;
EnumerableSet.UintSet private erc721PoolIdSet;
event DepositERC721(address indexed user, uint256 indexed pid, uint256 indexed erc721Id);
event WithdrawERC721(address indexed user, uint256 indexed pid, uint256 indexed erc721Id);
constructor() internal {}
// Add a new erc721 token 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 addERC721Pool(uint256 _allocPoint, address _721TokenAddr) public onlyAdmin {
uint256 pId = _add(_allocPoint, _721TokenAddr);
erc721PoolIdSet.add(pId);
}
// Deposit ERC721s to MasterChef for XIAONAN allocation.
function depositERC721(uint256 pId, uint256 erc721Id) public validAsERC721PId(pId) {
EnumerableSet.UintSet storage erc721Entities = erc721Pools[pId][_msgSender()];
require(erc721Entities.add(erc721Id), "StakingERC721: erc721 token already deposited");
require(_deposit(pId, 1) <= ERC721StakingMax, "StakingERC721: NFT staking count exceed its maximun");
IERC721 tokenProdiver = IERC721(poolInfo[pId].tokenAddress);
tokenProdiver.safeTransferFrom(_msgSender(), address(this), erc721Id);
emit DepositERC721(_msgSender(), pId, erc721Id);
}
// Withdraw ERC721s from MasterChef.
function withdrawERC721(uint256 pId, uint256 erc721Id) public validAsERC721PId(pId) {
EnumerableSet.UintSet storage erc721Entities = erc721Pools[pId][_msgSender()];
require(erc721Entities.remove(erc721Id), "StakingERC721: erc721 token not existe");
_withdraw(pId, 1);
IERC721 tokenProdiver = IERC721(poolInfo[pId].tokenAddress);
tokenProdiver.safeTransferFrom(address(this), _msgSender(), erc721Id);
emit WithdrawERC721(_msgSender(), pId, erc721Id);
}
/**
* @dev withdraw all staked erc1155 tokens in emergency, without tansfer pending tokens
*/
function emergencyWithdrawERC721(uint256 pId) public onEmergency validAsERC721PId(pId) {
uint256[] memory erc721Ids = pledgedERC721(pId, _msgSender());
_emergencyWithdraw(pId);
IERC721 tokenProdiver = IERC721(poolInfo[pId].tokenAddress); // get token provider by id
for (uint256 index = 0; index < erc721Ids.length; ++index)
tokenProdiver.safeTransferFrom(address(this), _msgSender(), erc721Ids[index]);
}
function pledgedERC721(uint256 pId, address _user) public view validAsERC721PId(pId) returns (uint256[] memory erc721Ids) {
EnumerableSet.UintSet storage erc721Entities = erc721Pools[pId][_user];
uint256 count = erc721Entities.length();
erc721Ids = new uint256[](count);
for (uint256 index = 0; index < count; ++index) erc721Ids[index] = erc721Entities.at(index);
}
function listERC721PoolIds() public view returns (uint256[] memory poolIds) {
poolIds = new uint256[](erc721PoolIdSet.length());
for (uint256 index = 0; index < poolIds.length; ++index) poolIds[index] = erc721PoolIdSet.at(index);
}
modifier validAsERC721PId(uint256 pId) {
require(erc721PoolIdSet.contains(pId), "StakingERC721: pool id not belong to defi ERC721");
_;
}
}
contract StakingYao is Ownable, StakingBase, StakingERC1155, StakingERC721, TimeUtil {
constructor(IERC20 yao_) public StakingBase(yao_) {
prodInit();
}
function prodInit() private {
miningBeginBlock = 12527500; //2021/05/29 13:54:19
periodes.push(PeriodeReleases({blockOffset: toBlocks(0 days), tokenPerBlock: calculeTokenPerBlock(60000 ether, 14 days)}));
periodes.push(PeriodeReleases({blockOffset: toBlocks(14 days), tokenPerBlock: calculeTokenPerBlock(25000 ether, 90 days)}));
periodes.push(PeriodeReleases({blockOffset: toBlocks(104 days), tokenPerBlock: calculeTokenPerBlock(10000 ether, 90 days)}));
periodes.push(PeriodeReleases({blockOffset: toBlocks(194 days), tokenPerBlock: calculeTokenPerBlock(3750 ether, 90 days)}));
periodes.push(PeriodeReleases({blockOffset: toBlocks(284 days), tokenPerBlock: calculeTokenPerBlock(1250 ether, 90 days)}));
periodes.push(PeriodeReleases({blockOffset: toBlocks(374 days), tokenPerBlock: 0}));
updateMiningTotal();
}
function updateMiningTotal() private {
uint256 sum = 0;
for (uint256 index = 1; index < periodes.length; ++index) {
sum += (periodes[index].blockOffset - periodes[index - 1].blockOffset) * periodes[index - 1].tokenPerBlock;
}
miningTotal = sum;
}
function calculeTokenPerBlock(uint256 amount, uint256 time) private pure returns (uint256) {
return amount / toBlocks(time);
}
} | update pool last reward block | pool.lastRewardBlock = block.number;
| 13,446,532 | [
1,
2725,
2845,
1142,
19890,
1203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
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);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
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;
}
}
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 () {
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 = block.timestamp + 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(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
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;
}
}
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;
}
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");
}
}
}
contract TokenTimelock {
using SafeERC20 for IERC20;
// ERC20 basic token contract being held
IERC20 private immutable _token;
// beneficiary of tokens after they are released
address private immutable _beneficiary;
// timestamp when token release is enabled
uint256 private immutable _releaseTime;
constructor(
IERC20 token_,
address beneficiary_,
uint256 releaseTime_
) {
require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time");
_token = token_;
_beneficiary = beneficiary_;
_releaseTime = releaseTime_;
}
/**
* @return the token being held.
*/
function token() public view virtual returns (IERC20) {
return _token;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view virtual returns (address) {
return _beneficiary;
}
/**
* @return the time when the tokens are released.
*/
function releaseTime() public view virtual returns (uint256) {
return _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public virtual {
require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time");
uint256 amount = token().balanceOf(address(this));
require(amount > 0, "TokenTimelock: no tokens to release");
token().safeTransfer(beneficiary(), amount);
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract AssetCoin is Context, IERC20, IERC20Metadata, 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 = "AssetCoin";
string private _symbol = "AC";
//IUniswapV2Router02 public immutable uniswapV2Router;
//address public immutable uniswapV2Pair;
address public dead = address(0x000000000000000000000000000000000000dEaD);
address public _fundPoolAddress;
uint public burnFee = 1;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
// uint256 public _maxTxAmount = 20 * 10**9 * 10**18;
// uint256 private numTokensSellToAddToLiquidity = 20 * 10**9 * 10**18;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor() {
_mint(msg.sender, 80 * 10**7 * 10**18);
//_burn(msg.sender, 3 * 10**8 * 10**9);
//IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3);
// 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;
}
/**
* @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 9;
}
/**
* @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];
}
function calculateBurnFee(uint256 _amount) public view returns (uint256) {
return _amount.mul(burnFee).div(
10**2
);
}
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
}
}
/**
* @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 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");
unchecked {
_balances[sender] = senderBalance - amount;
}
uint256 tokensToBurn = calculateBurnFee(amount);
uint256 tokenToTransfer = amount.sub(tokensToBurn);
_balances[recipient] += tokenToTransfer;
_totalSupply -= tokensToBurn;
emit Transfer(sender, recipient, tokenToTransfer);
emit Transfer(sender, dead, tokensToBurn);
}
/** @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);
}
/**
* @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, dead, amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, dead, 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 {}
} | * @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");
unchecked {
_balances[sender] = senderBalance - amount;
}
uint256 tokensToBurn = calculateBurnFee(amount);
uint256 tokenToTransfer = amount.sub(tokensToBurn);
_balances[recipient] += tokenToTransfer;
_totalSupply -= tokensToBurn;
emit Transfer(sender, recipient, tokenToTransfer);
emit Transfer(sender, dead, tokensToBurn);
}
| 470,434 | [
1,
19297,
2430,
1375,
8949,
68,
628,
1375,
15330,
68,
358,
1375,
20367,
8338,
1220,
353,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
15330,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
203,
3639,
2254,
5034,
5793,
13937,
273,
389,
70,
26488,
63,
15330,
15533,
203,
3639,
2583,
12,
15330,
13937,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
15330,
65,
273,
5793,
13937,
300,
3844,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
2430,
774,
38,
321,
273,
4604,
38,
321,
14667,
12,
8949,
1769,
203,
3639,
2254,
5034,
1147,
774,
5912,
273,
3844,
18,
1717,
12,
7860,
774,
38,
321,
1769,
203,
3639,
389,
70,
26488,
63,
20367,
65,
1011,
1147,
774,
5912,
31,
203,
3639,
389,
4963,
3088,
1283,
3947,
2430,
774,
38,
321,
31,
203,
3639,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
16,
1147,
774,
5912,
1769,
203,
3639,
3626,
12279,
12,
15330,
16,
8363,
16,
2430,
774,
38,
321,
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
] |
./partial_match/1/0xB985eA1be961f7c4A4C45504444C02c88c4fdEF9/sources/src/MultiClaimsHatter.sol | * @notice Wrapper around a HatsModuleFactory. Deploys new HatsModule instances and sets the claimability type of multiple hats. @param _factory The HatsModuleFactory instance that will deploy the modules @param _implementations The addresses of the implementation contracts of which to deploy a clone @param _moduleHatIds The hats for which to deploy a HatsModule. @param _otherImmutableArgsArray Other immutable args to pass to the clones as immutable storage. @param _initDataArray The encoded data to pass to the `setUp` functions of the new HatsModule instances. Leave @param _hatIds The IDs of the hats to set claimability for @param _claimTypes New claimability types for each hat @return success True if all modules were successfully created and the claimability types were set/ | function setHatsClaimabilityAndCreateModules(
HatsModuleFactory _factory,
address[] calldata _implementations,
uint256[] calldata _moduleHatIds,
bytes[] calldata _otherImmutableArgsArray,
bytes[] calldata _initDataArray,
uint256[] memory _hatIds,
ClaimType[] memory _claimTypes
) public returns (bool success) {
uint256 length = _hatIds.length;
if (_claimTypes.length != length) {
revert MultiClaimsHatter_ArrayLengthMismatch();
}
uint256 hatId;
for (uint256 i; i < length;) {
hatId = _hatIds[i];
if (!HATS().isAdminOfHat(msg.sender, hatId)) revert MultiClaimsHatter_NotAdminOfHat(msg.sender, hatId);
hatToClaimType[hatId] = _claimTypes[i];
unchecked {
++i;
}
}
success = _factory.batchCreateHatsModule(_implementations, _moduleHatIds, _otherImmutableArgsArray, _initDataArray);
emit HatsClaimabilitySet(_hatIds, _claimTypes);
}
CLAIMING FUNCTIONS
| 2,750,272 | [
1,
3611,
6740,
279,
670,
2323,
3120,
1733,
18,
4019,
383,
1900,
394,
670,
2323,
3120,
3884,
471,
1678,
326,
7516,
2967,
618,
434,
3229,
366,
2323,
18,
225,
389,
6848,
1021,
670,
2323,
3120,
1733,
791,
716,
903,
7286,
326,
4381,
225,
389,
10442,
1012,
1021,
6138,
434,
326,
4471,
20092,
434,
1492,
358,
7286,
279,
3236,
225,
389,
2978,
44,
270,
2673,
1021,
366,
2323,
364,
1492,
358,
7286,
279,
670,
2323,
3120,
18,
225,
389,
3011,
16014,
2615,
1076,
4673,
11732,
833,
358,
1342,
358,
326,
927,
5322,
487,
11732,
2502,
18,
225,
389,
2738,
751,
1076,
1021,
3749,
501,
358,
1342,
358,
326,
1375,
542,
1211,
68,
4186,
434,
326,
394,
670,
2323,
3120,
3884,
18,
21131,
225,
389,
11304,
2673,
1021,
7115,
434,
326,
366,
2323,
358,
444,
7516,
2967,
364,
225,
389,
14784,
2016,
1166,
7516,
2967,
1953,
364,
1517,
366,
270,
327,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
225,
445,
444,
44,
2323,
9762,
2967,
1876,
1684,
7782,
12,
203,
565,
670,
2323,
3120,
1733,
389,
6848,
16,
203,
565,
1758,
8526,
745,
892,
389,
10442,
1012,
16,
203,
565,
2254,
5034,
8526,
745,
892,
389,
2978,
44,
270,
2673,
16,
203,
565,
1731,
8526,
745,
892,
389,
3011,
16014,
2615,
1076,
16,
203,
565,
1731,
8526,
745,
892,
389,
2738,
751,
1076,
16,
203,
565,
2254,
5034,
8526,
3778,
389,
11304,
2673,
16,
203,
565,
18381,
559,
8526,
3778,
389,
14784,
2016,
203,
225,
262,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
565,
2254,
5034,
769,
273,
389,
11304,
2673,
18,
2469,
31,
203,
565,
309,
261,
67,
14784,
2016,
18,
2469,
480,
769,
13,
288,
203,
1377,
15226,
5991,
15925,
44,
9293,
67,
1076,
1782,
16901,
5621,
203,
565,
289,
203,
203,
565,
2254,
5034,
366,
270,
548,
31,
203,
565,
364,
261,
11890,
5034,
277,
31,
277,
411,
769,
30943,
288,
203,
1377,
366,
270,
548,
273,
389,
11304,
2673,
63,
77,
15533,
203,
1377,
309,
16051,
44,
17813,
7675,
291,
4446,
951,
44,
270,
12,
3576,
18,
15330,
16,
366,
270,
548,
3719,
15226,
5991,
15925,
44,
9293,
67,
1248,
4446,
951,
44,
270,
12,
3576,
18,
15330,
16,
366,
270,
548,
1769,
203,
1377,
366,
270,
774,
9762,
559,
63,
11304,
548,
65,
273,
389,
14784,
2016,
63,
77,
15533,
203,
1377,
22893,
288,
203,
3639,
965,
77,
31,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
2216,
273,
389,
6848,
18,
5303,
1684,
44,
2
] |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// Lib: Safe Math
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256 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 (uint256);
function balanceOf(address tokenOwner)
public
constant
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
public
constant
returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens)
public
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint256 tokens
);
}
/**
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;
}
/**
ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers
*/
contract TKT is ERC20Interface, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint256 public _totalSupply;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "TKT";
name = "TKT Token";
decimals = 4;
_totalSupply = 10000000000000;
// metamask - michael vergoz
// balances[0xf1E2C564b0182Fba1BfA07c196c443DeB10e7De4] = _totalSupply;
// emit Transfer(
// address(0),
// 0xf1E2C564b0182Fba1BfA07c196c443DeB10e7De4,
// _totalSupply
// );
balances[0x20e99E8DB53408e0033119A10Bcc2921C97B99eA] = _totalSupply;
emit Transfer(
address(0),
0x20e99E8DB53408e0033119A10Bcc2921C97B99eA,
_totalSupply
);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint256) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner)
public
constant
returns (uint256 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, uint256 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;
}
// ------------------------------------------------------------------------
// 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, uint256 tokens)
public
returns (bool success)
{
allowed[msg.sender][spender] = tokens;
emit 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,
uint256 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;
}
// ------------------------------------------------------------------------
// 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 (uint256 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,
uint256 tokens,
bytes data
) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(
msg.sender,
tokens,
this,
data
);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function() public payable {
revert();
}
} | ------------------------------------------------------------------------ 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 (uint256 remaining)
{
return allowed[tokenOwner][spender];
}
| 62,167 | [
1,
29461,
2860,
326,
3844,
434,
2430,
20412,
635,
326,
3410,
716,
848,
506,
906,
4193,
358,
326,
17571,
264,
1807,
2236,
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,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1699,
1359,
12,
2867,
1147,
5541,
16,
1758,
17571,
264,
13,
203,
3639,
1071,
203,
3639,
5381,
203,
3639,
1135,
261,
11890,
5034,
4463,
13,
203,
565,
288,
203,
3639,
327,
2935,
63,
2316,
5541,
6362,
87,
1302,
264,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.17;
/**
* @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;
/**
* @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 {
if (newOwner != address(0)) {
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 allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require (!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require (paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public returns (bool) {
paused = false;
Unpause();
return true;
}
}
/**
* @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 constant 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 constant 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 SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
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]);
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 constant 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];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// ***********************************************************************************
// *************************** END OF THE BASIC **************************************
// ***********************************************************************************
contract IrisTokenPrivatSale is Ownable, Pausable{
using SafeMath for uint256;
// The token being sold
address public multiSig;
// ***************************
// amount of raised money in wei
uint256 public weiRaised;
event HostEther(address indexed buyer, uint256 value);
event TokenPlaced(address indexed beneficiary, uint256 amount);
event SetWallet(address _newWallet);
event SendedEtherToMultiSig(address walletaddress, uint256 amountofether);
function setWallet(address _newWallet) public onlyOwner {
multiSig = _newWallet;
SetWallet(_newWallet);
}
function IrisTokenPrivatSale() public {
// *************************************
multiSig = 0x02cb1ADc98e984A67a3d892Dbb7eD72b36dA7b07; // IRIS multiSig Wallet Address
//**************************************
}
// low level token purchase function
function buyTokens(address buyer, uint256 amount) whenNotPaused internal {
require (multiSig != 0x0);
require (msg.value >= 2 ether);
// update state
weiRaised = weiRaised.add(amount);
HostEther(buyer, amount);
// send the ether to the MultiSig Wallet
multiSig.transfer(this.balance); // better in case any other ether ends up here
SendedEtherToMultiSig(multiSig,amount);
}
// fallback function can be used to buy tokens
function () public payable {
buyTokens(msg.sender, msg.value);
}
function emergencyERC20Drain( ERC20 oddToken, uint amount ) public onlyOwner{
oddToken.transfer(owner, 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) 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);
Transfer(msg.sender, _to, _value);
return true;
}
| 6,304,083 | [
1,
13866,
1147,
364,
279,
1269,
1758,
225,
389,
869,
1021,
1758,
358,
7412,
358,
18,
225,
389,
1132,
1021,
3844,
358,
506,
906,
4193,
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
] | [
1,
1,
1,
1,
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,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
15329,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
1132,
1648,
324,
26488,
63,
3576,
18,
15330,
19226,
203,
377,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/77/0xcA47f86f29Ab274257792a2Cf24B7299d449cF06/sources/deploy/contracts/synthereum-pool/v5/LiquidityPool.sol | * @notice Called by a source Pool's `exchange` function to mint destination tokens @notice This functon can be called only by a pool registered in the PoolRegister contract @param collateralAmount The amount of collateral to use from the source Pool @param numTokens The number of new tokens to mint @param recipient Recipient to which send synthetic token minted/ | function exchangeMint(
uint256 collateralAmount,
uint256 numTokens,
address recipient
) external override notEmergencyShutdown nonReentrant {
poolStorage.exchangeMint(
lpPosition,
feeStatus,
FixedPoint.Unsigned(collateralAmount),
FixedPoint.Unsigned(numTokens),
recipient
);
}
| 5,047,223 | [
1,
8185,
635,
279,
1084,
8828,
1807,
1375,
16641,
68,
445,
358,
312,
474,
2929,
2430,
225,
1220,
12882,
265,
848,
506,
2566,
1338,
635,
279,
2845,
4104,
316,
326,
8828,
3996,
6835,
225,
4508,
2045,
287,
6275,
1021,
3844,
434,
4508,
2045,
287,
358,
999,
628,
326,
1084,
8828,
225,
818,
5157,
1021,
1300,
434,
394,
2430,
358,
312,
474,
225,
8027,
23550,
358,
1492,
1366,
25535,
1147,
312,
474,
329,
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,
225,
445,
7829,
49,
474,
12,
203,
565,
2254,
5034,
4508,
2045,
287,
6275,
16,
203,
565,
2254,
5034,
818,
5157,
16,
203,
565,
1758,
8027,
203,
225,
262,
3903,
3849,
486,
1514,
24530,
10961,
1661,
426,
8230,
970,
288,
203,
565,
2845,
3245,
18,
16641,
49,
474,
12,
203,
1377,
12423,
2555,
16,
203,
1377,
14036,
1482,
16,
203,
1377,
15038,
2148,
18,
13290,
12,
12910,
2045,
287,
6275,
3631,
203,
1377,
15038,
2148,
18,
13290,
12,
2107,
5157,
3631,
203,
1377,
8027,
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
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
import { IERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import { IERC20WithCheckpointing } from "./aragonone/IERC20WithCheckpointing.sol";
import { Checkpointing } from "./aragonone/Checkpointing.sol";
import { CheckpointingHelpers } from "./aragonone/CheckpointingHelpers.sol";
import { ERC20ViewOnly } from "../utils/ERC20ViewOnly.sol";
import { Decimal } from "../utils/Decimal.sol";
import { DecimalERC20 } from "../utils/DecimalERC20.sol";
import { BlockContext } from "../utils/BlockContext.sol";
import { PerpFiOwnableUpgrade } from "../utils/PerpFiOwnableUpgrade.sol";
import { AddressArray } from "../utils/AddressArray.sol";
import { IStakeModule } from "../interface/IStakeModule.sol";
contract StakedPerpToken is IERC20WithCheckpointing, ERC20ViewOnly, DecimalERC20, PerpFiOwnableUpgrade, BlockContext {
using Checkpointing for Checkpointing.History;
using CheckpointingHelpers for uint256;
using SafeMath for uint256;
using AddressArray for address[];
uint256 public constant TOKEN_AMOUNT_LIMIT = 20;
//
// EVENTS
//
event Staked(address staker, uint256 amount);
event Unstaked(address staker, uint256 amount);
event Withdrawn(address staker, uint256 amount);
event StakeModuleAdded(address stakedModule);
event StakeModuleRemoved(address stakedModule);
//**********************************************************//
// The below state variables can not change the order //
//**********************************************************//
// ERC20 variables
string public name;
string public symbol;
uint8 public decimals;
// ERC20 variables
// Checkpointing total supply of the deposited token
Checkpointing.History internal totalSupplyHistory;
// Checkpointing balances of the deposited token by staker
mapping(address => Checkpointing.History) internal balancesHistory;
// staker => the time staker can withdraw PERP
mapping(address => uint256) public stakerCooldown;
// staker => PERP staker can withdraw
mapping(address => Decimal.decimal) public stakerWithdrawPendingBalance;
address[] public stakeModules;
IERC20 public perpToken;
uint256 public cooldownPeriod;
//**********************************************************//
// The above state variables can not change the order //
//**********************************************************//
//◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤ add state variables below ◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤//
//◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣ add state variables above ◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣//
uint256[50] private __gap;
//
// FUNCTIONS
//
function initialize(IERC20 _perpToken, uint256 _cooldownPeriod) external initializer {
require(address(_perpToken) != address(0), "Invalid input.");
__Ownable_init();
name = "Staked Perpetual";
symbol = "sPERP";
decimals = 18;
perpToken = _perpToken;
cooldownPeriod = _cooldownPeriod;
}
function stake(Decimal.decimal calldata _amount) external {
requireNonZeroAmount(_amount);
requireStakeModuleExisted();
address msgSender = _msgSender();
// copy calldata amount to memory
Decimal.decimal memory amount = _amount;
// stake after unstake is allowed, and the states mutated by unstake() will being undo
if (stakerWithdrawPendingBalance[msgSender].toUint() != 0) {
amount = amount.addD(stakerWithdrawPendingBalance[msgSender]);
delete stakerWithdrawPendingBalance[msgSender];
delete stakerCooldown[msgSender];
}
// if staking after unstaking, the amount to be transferred does not need to be updated
_transferFrom(perpToken, msgSender, address(this), _amount);
_mint(msgSender, amount);
// Have to update balance first
for (uint256 i; i < stakeModules.length; i++) {
IStakeModule(stakeModules[i]).notifyStakeChanged(msgSender);
}
emit Staked(msgSender, amount.toUint());
}
// this function mutates stakerWithdrawPendingBalance, stakerCooldown, addTotalSupplyCheckPoint,
// addPersonalBalanceCheckPoint, burn
function unstake() external {
address msgSender = _msgSender();
requireStakeModuleExisted();
require(stakerWithdrawPendingBalance[msgSender].toUint() == 0, "Need to withdraw first");
Decimal.decimal memory balance = Decimal.decimal(balancesHistory[msgSender].latestValue());
requireNonZeroAmount(balance);
_burn(msgSender, balance);
stakerCooldown[msgSender] = _blockTimestamp().add(cooldownPeriod);
stakerWithdrawPendingBalance[msgSender] = balance;
// Have to update balance first
for (uint256 i; i < stakeModules.length; i++) {
IStakeModule(stakeModules[i]).notifyStakeChanged(msgSender);
}
emit Unstaked(msgSender, balance.toUint());
}
function withdraw() external {
address msgSender = _msgSender();
Decimal.decimal memory balance = stakerWithdrawPendingBalance[msgSender];
requireNonZeroAmount(balance);
// there won't be a case that cooldown == 0 && balance == 0
require(_blockTimestamp() >= stakerCooldown[msgSender], "Still in cooldown");
delete stakerWithdrawPendingBalance[msgSender];
delete stakerCooldown[msgSender];
_transfer(perpToken, msgSender, balance);
emit Withdrawn(msgSender, balance.toUint());
}
function addStakeModule(IStakeModule _stakeModule) external onlyOwner {
require(stakeModules.length < TOKEN_AMOUNT_LIMIT, "exceed stakeModule amount limit");
require(stakeModules.add(address(_stakeModule)), "invalid input");
emit StakeModuleAdded(address(_stakeModule));
}
function removeStakeModule(IStakeModule _stakeModule) external onlyOwner {
address removedAddr = stakeModules.remove(address(_stakeModule));
require(removedAddr != address(0), "stakeModule does not exist");
require(removedAddr == address(_stakeModule), "remove wrong stakeModule");
emit StakeModuleRemoved(address(_stakeModule));
}
//
// VIEW FUNCTIONS
//
//
// override: ERC20
//
function balanceOf(address _owner) public view override returns (uint256) {
return _balanceOfAt(_owner, _blockNumber()).toUint();
}
function totalSupply() public view override returns (uint256) {
return _totalSupplyAt(_blockNumber()).toUint();
}
//
// override: IERC20WithCheckpointing
//
function balanceOfAt(address _owner, uint256 __blockNumber) external view override returns (uint256) {
return _balanceOfAt(_owner, __blockNumber).toUint();
}
function totalSupplyAt(uint256 __blockNumber) external view override returns (uint256) {
return _totalSupplyAt(__blockNumber).toUint();
}
//
// EXTERNAL FUNCTIONS
//
function getStakeModuleLength() external view returns (uint256) {
return stakeModules.length;
}
//
// INTERNAL FUNCTIONS
//
function isStakeModuleExisted(IStakeModule _stakeModule) public view returns (bool) {
return stakeModules.isExisted(address(_stakeModule));
}
function _mint(address account, Decimal.decimal memory amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
Decimal.decimal memory balance = Decimal.decimal(balanceOf(account));
Decimal.decimal memory newBalance = balance.addD(amount);
Decimal.decimal memory currentTotalSupply = Decimal.decimal(totalSupply());
Decimal.decimal memory newTotalSupply = currentTotalSupply.addD(amount);
uint256 blockNumber = _blockNumber();
addPersonalBalanceCheckPoint(account, blockNumber, newBalance);
addTotalSupplyCheckPoint(blockNumber, newTotalSupply);
emit Transfer(address(0), account, amount.toUint());
}
function _burn(address account, Decimal.decimal memory amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
Decimal.decimal memory balance = Decimal.decimal(balanceOf(account));
Decimal.decimal memory newBalance = balance.subD(amount);
Decimal.decimal memory currentTotalSupply = Decimal.decimal(totalSupply());
Decimal.decimal memory newTotalSupply = currentTotalSupply.subD(amount);
uint256 blockNumber = _blockNumber();
addPersonalBalanceCheckPoint(account, blockNumber, newBalance);
addTotalSupplyCheckPoint(blockNumber, newTotalSupply);
emit Transfer(account, address(0), amount.toUint());
}
function addTotalSupplyCheckPoint(uint256 __blockNumber, Decimal.decimal memory _amount) internal {
totalSupplyHistory.addCheckpoint(__blockNumber.toUint64Time(), _amount.toUint().toUint192Value());
}
function addPersonalBalanceCheckPoint(
address _staker,
uint256 __blockNumber,
Decimal.decimal memory _amount
) internal {
balancesHistory[_staker].addCheckpoint(__blockNumber.toUint64Time(), _amount.toUint().toUint192Value());
}
function _balanceOfAt(address _owner, uint256 __blockNumber) internal view returns (Decimal.decimal memory) {
return Decimal.decimal(balancesHistory[_owner].getValueAt(__blockNumber.toUint64Time()));
}
function _totalSupplyAt(uint256 __blockNumber) internal view returns (Decimal.decimal memory) {
return Decimal.decimal(totalSupplyHistory.getValueAt(__blockNumber.toUint64Time()));
}
//
// REQUIRE FUNCTIONS
//
function requireNonZeroAmount(Decimal.decimal memory _amount) private pure {
require(_amount.toUint() > 0, "Amount is 0");
}
function requireStakeModuleExisted() internal view {
require(stakeModules.length > 0, "no stakeModule");
}
}
// source: https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/interfaces/IERC20WithCheckpointing.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.6.9;
interface IERC20WithCheckpointing {
function balanceOfAt(address _owner, uint256 _blockNumber) external view returns (uint256);
function totalSupplyAt(uint256 _blockNumber) external view returns (uint256);
}
// source: https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.6.9;
/**
* @title Checkpointing
* @notice Checkpointing library for keeping track of historical values based on an arbitrary time
* unit (e.g. seconds or block numbers).
* @dev Inspired by:
* - MiniMe token (https://github.com/aragon/minime/blob/master/contracts/MiniMeToken.sol)
* - Staking (https://github.com/aragon/staking/blob/master/contracts/Checkpointing.sol)
*/
library Checkpointing {
string private constant ERROR_PAST_CHECKPOINT = "CHECKPOINT_PAST_CHECKPOINT";
struct Checkpoint {
uint64 time;
uint192 value;
}
struct History {
Checkpoint[] history;
}
function addCheckpoint(
History storage _self,
uint64 _time,
uint192 _value
) internal {
uint256 length = _self.history.length;
if (length == 0) {
_self.history.push(Checkpoint(_time, _value));
} else {
Checkpoint storage currentCheckpoint = _self.history[length - 1];
uint256 currentCheckpointTime = uint256(currentCheckpoint.time);
if (_time > currentCheckpointTime) {
_self.history.push(Checkpoint(_time, _value));
} else if (_time == currentCheckpointTime) {
currentCheckpoint.value = _value;
} else {
// ensure list ordering
revert(ERROR_PAST_CHECKPOINT);
}
}
}
function getValueAt(History storage _self, uint64 _time) internal view returns (uint256) {
return _getValueAt(_self, _time);
}
function lastUpdated(History storage _self) internal view returns (uint256) {
uint256 length = _self.history.length;
if (length > 0) {
return uint256(_self.history[length - 1].time);
}
return 0;
}
function latestValue(History storage _self) internal view returns (uint256) {
uint256 length = _self.history.length;
if (length > 0) {
return uint256(_self.history[length - 1].value);
}
return 0;
}
function _getValueAt(History storage _self, uint64 _time) private view returns (uint256) {
uint256 length = _self.history.length;
// Short circuit if there's no checkpoints yet
// Note that this also lets us avoid using SafeMath later on, as we've established that
// there must be at least one checkpoint
if (length == 0) {
return 0;
}
// Check last checkpoint
uint256 lastIndex = length - 1;
Checkpoint storage lastCheckpoint = _self.history[lastIndex];
if (_time >= lastCheckpoint.time) {
return uint256(lastCheckpoint.value);
}
// Check first checkpoint (if not already checked with the above check on last)
if (length == 1 || _time < _self.history[0].time) {
return 0;
}
// Do binary search
// As we've already checked both ends, we don't need to check the last checkpoint again
uint256 low = 0;
uint256 high = lastIndex - 1;
while (high > low) {
uint256 mid = (high + low + 1) / 2; // average, ceil round
Checkpoint storage checkpoint = _self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// Note that we don't need SafeMath here because mid must always be greater than 0
// from the while condition
high = mid - 1;
} else {
// _time == midTime
return uint256(checkpoint.value);
}
}
return uint256(_self.history[low].value);
}
}
// source: https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/CheckpointingHelpers.sol
pragma solidity 0.6.9;
library CheckpointingHelpers {
uint256 private constant MAX_UINT64 = uint64(-1);
uint256 private constant MAX_UINT192 = uint192(-1);
string private constant ERROR_UINT64_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
string private constant ERROR_UINT192_TOO_BIG = "UINT192_NUMBER_TOO_BIG";
function toUint64Time(uint256 _a) internal pure returns (uint64) {
require(_a <= MAX_UINT64, ERROR_UINT64_TOO_BIG);
return uint64(_a);
}
function toUint192Value(uint256 _a) internal pure returns (uint192) {
require(_a <= MAX_UINT192, ERROR_UINT192_TOO_BIG);
return uint192(_a);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
import { IERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
abstract contract ERC20ViewOnly is IERC20 {
function transfer(address, uint256) public virtual override returns (bool) {
revert("transfer() is not supported");
}
function transferFrom(
address,
address,
uint256
) public virtual override returns (bool) {
revert("transferFrom() is not supported");
}
function approve(address, uint256) public virtual override returns (bool) {
revert("approve() is not supported");
}
function allowance(address, address) public view virtual override returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
import { SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import { DecimalMath } from "./DecimalMath.sol";
library Decimal {
using DecimalMath for uint256;
using SafeMath for uint256;
struct decimal {
uint256 d;
}
function zero() internal pure returns (decimal memory) {
return decimal(0);
}
function one() internal pure returns (decimal memory) {
return decimal(DecimalMath.unit(18));
}
function toUint(decimal memory x) internal pure returns (uint256) {
return x.d;
}
function modD(decimal memory x, decimal memory y) internal pure returns (decimal memory) {
return decimal(x.d.mul(DecimalMath.unit(18)) % y.d);
}
function cmp(decimal memory x, decimal memory y) internal pure returns (int8) {
if (x.d > y.d) {
return 1;
} else if (x.d < y.d) {
return -1;
}
return 0;
}
/// @dev add two decimals
function addD(decimal memory x, decimal memory y) internal pure returns (decimal memory) {
decimal memory t;
t.d = x.d.add(y.d);
return t;
}
/// @dev subtract two decimals
function subD(decimal memory x, decimal memory y) internal pure returns (decimal memory) {
decimal memory t;
t.d = x.d.sub(y.d);
return t;
}
/// @dev multiple two decimals
function mulD(decimal memory x, decimal memory y) internal pure returns (decimal memory) {
decimal memory t;
t.d = x.d.muld(y.d);
return t;
}
/// @dev multiple a decimal by a uint256
function mulScalar(decimal memory x, uint256 y) internal pure returns (decimal memory) {
decimal memory t;
t.d = x.d.mul(y);
return t;
}
/// @dev divide two decimals
function divD(decimal memory x, decimal memory y) internal pure returns (decimal memory) {
decimal memory t;
t.d = x.d.divd(y.d);
return t;
}
/// @dev divide a decimal by a uint256
function divScalar(decimal memory x, uint256 y) internal pure returns (decimal memory) {
decimal memory t;
t.d = x.d.div(y);
return t;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
import { SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/// @dev Implements simple fixed point math add, sub, mul and div operations.
/// @author Alberto Cuesta Cañada
library DecimalMath {
using SafeMath for uint256;
/// @dev Returns 1 in the fixed point representation, with `decimals` decimals.
function unit(uint8 decimals) internal pure returns (uint256) {
return 10**uint256(decimals);
}
/// @dev Adds x and y, assuming they are both fixed point with 18 decimals.
function addd(uint256 x, uint256 y) internal pure returns (uint256) {
return x.add(y);
}
/// @dev Subtracts y from x, assuming they are both fixed point with 18 decimals.
function subd(uint256 x, uint256 y) internal pure returns (uint256) {
return x.sub(y);
}
/// @dev Multiplies x and y, assuming they are both fixed point with 18 digits.
function muld(uint256 x, uint256 y) internal pure returns (uint256) {
return muld(x, y, 18);
}
/// @dev Multiplies x and y, assuming they are both fixed point with `decimals` digits.
function muld(
uint256 x,
uint256 y,
uint8 decimals
) internal pure returns (uint256) {
return x.mul(y).div(unit(decimals));
}
/// @dev Divides x between y, assuming they are both fixed point with 18 digits.
function divd(uint256 x, uint256 y) internal pure returns (uint256) {
return divd(x, y, 18);
}
/// @dev Divides x between y, assuming they are both fixed point with `decimals` digits.
function divd(
uint256 x,
uint256 y,
uint8 decimals
) internal pure returns (uint256) {
return x.mul(unit(decimals)).div(y);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
import { IERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import { Decimal } from "./Decimal.sol";
abstract contract DecimalERC20 {
using SafeMath for uint256;
using Decimal for Decimal.decimal;
mapping(address => uint256) private decimalMap;
//◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤ add state variables below ◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤//
//◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣ add state variables above ◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣//
uint256[50] private __gap;
//
// INTERNAL functions
//
// CAUTION: do not input _from == _to s.t. this function will always fail
function _transfer(
IERC20 _token,
address _to,
Decimal.decimal memory _value
) internal {
_updateDecimal(address(_token));
Decimal.decimal memory balanceBefore = _balanceOf(_token, _to);
uint256 roundedDownValue = _toUint(_token, _value);
// solhint-disable avoid-low-level-calls
(bool success, bytes memory data) =
address(_token).call(abi.encodeWithSelector(_token.transfer.selector, _to, roundedDownValue));
require(success && (data.length == 0 || abi.decode(data, (bool))), "DecimalERC20: transfer failed");
_validateBalance(_token, _to, roundedDownValue, balanceBefore);
}
function _transferFrom(
IERC20 _token,
address _from,
address _to,
Decimal.decimal memory _value
) internal {
_updateDecimal(address(_token));
Decimal.decimal memory balanceBefore = _balanceOf(_token, _to);
uint256 roundedDownValue = _toUint(_token, _value);
// solhint-disable avoid-low-level-calls
(bool success, bytes memory data) =
address(_token).call(abi.encodeWithSelector(_token.transferFrom.selector, _from, _to, roundedDownValue));
require(success && (data.length == 0 || abi.decode(data, (bool))), "DecimalERC20: transferFrom failed");
_validateBalance(_token, _to, roundedDownValue, balanceBefore);
}
function _approve(
IERC20 _token,
address _spender,
Decimal.decimal memory _value
) internal {
_updateDecimal(address(_token));
// to be compatible with some erc20 tokens like USDT
__approve(_token, _spender, Decimal.zero());
__approve(_token, _spender, _value);
}
//
// VIEW
//
function _allowance(
IERC20 _token,
address _owner,
address _spender
) internal view returns (Decimal.decimal memory) {
return _toDecimal(_token, _token.allowance(_owner, _spender));
}
function _balanceOf(IERC20 _token, address _owner) internal view returns (Decimal.decimal memory) {
return _toDecimal(_token, _token.balanceOf(_owner));
}
function _totalSupply(IERC20 _token) internal view returns (Decimal.decimal memory) {
return _toDecimal(_token, _token.totalSupply());
}
function _toDecimal(IERC20 _token, uint256 _number) internal view returns (Decimal.decimal memory) {
uint256 tokenDecimals = _getTokenDecimals(address(_token));
if (tokenDecimals >= 18) {
return Decimal.decimal(_number.div(10**(tokenDecimals.sub(18))));
}
return Decimal.decimal(_number.mul(10**(uint256(18).sub(tokenDecimals))));
}
function _toUint(IERC20 _token, Decimal.decimal memory _decimal) internal view returns (uint256) {
uint256 tokenDecimals = _getTokenDecimals(address(_token));
if (tokenDecimals >= 18) {
return _decimal.toUint().mul(10**(tokenDecimals.sub(18)));
}
return _decimal.toUint().div(10**(uint256(18).sub(tokenDecimals)));
}
function _getTokenDecimals(address _token) internal view returns (uint256) {
uint256 tokenDecimals = decimalMap[_token];
if (tokenDecimals == 0) {
(bool success, bytes memory data) = _token.staticcall(abi.encodeWithSignature("decimals()"));
require(success && data.length != 0, "DecimalERC20: get decimals failed");
tokenDecimals = abi.decode(data, (uint256));
}
return tokenDecimals;
}
//
// PRIVATE
//
function _updateDecimal(address _token) private {
uint256 tokenDecimals = _getTokenDecimals(_token);
if (decimalMap[_token] != tokenDecimals) {
decimalMap[_token] = tokenDecimals;
}
}
function __approve(
IERC20 _token,
address _spender,
Decimal.decimal memory _value
) private {
// solhint-disable avoid-low-level-calls
(bool success, bytes memory data) =
address(_token).call(abi.encodeWithSelector(_token.approve.selector, _spender, _toUint(_token, _value)));
require(success && (data.length == 0 || abi.decode(data, (bool))), "DecimalERC20: approve failed");
}
// To prevent from deflationary token, check receiver's balance is as expectation.
function _validateBalance(
IERC20 _token,
address _to,
uint256 _roundedDownValue,
Decimal.decimal memory _balanceBefore
) private view {
require(
_balanceOf(_token, _to).cmp(_balanceBefore.addD(_toDecimal(_token, _roundedDownValue))) == 0,
"DecimalERC20: balance inconsistent"
);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
// wrap block.xxx functions for testing
// only support timestamp and number so far
abstract contract BlockContext {
//◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤ add state variables below ◥◤◥◤◥◤◥◤◥◤◥◤◥◤◥◤//
//◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣ add state variables above ◢◣◢◣◢◣◢◣◢◣◢◣◢◣◢◣//
uint256[50] private __gap;
function _blockTimestamp() internal view virtual returns (uint256) {
return block.timestamp;
}
function _blockNumber() internal view virtual returns (uint256) {
return block.number;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
import { ContextUpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
// copy from openzeppelin Ownable, only modify how the owner transfer
/**
* @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 PerpFiOwnableUpgrade is ContextUpgradeSafe {
address private _owner;
address private _candidate;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
function candidate() public view returns (address) {
return _candidate;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "PerpFiOwnableUpgrade: 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 Set ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function setOwner(address newOwner) public onlyOwner {
require(newOwner != address(0), "PerpFiOwnableUpgrade: zero address");
require(newOwner != _owner, "PerpFiOwnableUpgrade: same as original");
require(newOwner != _candidate, "PerpFiOwnableUpgrade: same as candidate");
_candidate = newOwner;
}
/**
* @dev Transfers ownership of the contract to a new account (`_candidate`).
* Can only be called by the new owner.
*/
function updateOwner() public {
require(_candidate != address(0), "PerpFiOwnableUpgrade: candidate is zero address");
require(_candidate == _msgSender(), "PerpFiOwnableUpgrade: not the new owner");
emit OwnershipTransferred(_owner, _candidate);
_owner = _candidate;
_candidate = address(0);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
library AddressArray {
function add(address[] storage addrArray, address addr) internal returns (bool) {
if (addr == address(0) || isExisted(addrArray, addr)) {
return false;
}
addrArray.push(addr);
return true;
}
function remove(address[] storage addrArray, address addr) internal returns (address) {
if (addr == address(0)) {
return address(0);
}
uint256 lengthOfArray = addrArray.length;
for (uint256 i; i < lengthOfArray; i++) {
if (addr == addrArray[i]) {
if (i != lengthOfArray - 1) {
addrArray[i] = addrArray[lengthOfArray - 1];
}
addrArray.pop();
return addr;
}
}
return address(0);
}
function isExisted(address[] memory addrArray, address addr) internal pure returns (bool) {
for (uint256 i; i < addrArray.length; i++) {
if (addr == addrArray[i]) return true;
}
return false;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.9;
interface IStakeModule {
function notifyStakeChanged(address staker) external;
}
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.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;
import "../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 ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
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;
}
| there won't be a case that cooldown == 0 && balance == 0 | function withdraw() external {
address msgSender = _msgSender();
Decimal.decimal memory balance = stakerWithdrawPendingBalance[msgSender];
requireNonZeroAmount(balance);
require(_blockTimestamp() >= stakerCooldown[msgSender], "Still in cooldown");
delete stakerWithdrawPendingBalance[msgSender];
delete stakerCooldown[msgSender];
_transfer(perpToken, msgSender, balance);
emit Withdrawn(msgSender, balance.toUint());
}
| 13,612,640 | [
1,
18664,
8462,
1404,
506,
279,
648,
716,
27367,
2378,
422,
374,
597,
11013,
422,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1435,
3903,
288,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
11322,
18,
12586,
3778,
11013,
273,
384,
6388,
1190,
9446,
8579,
13937,
63,
3576,
12021,
15533,
203,
3639,
2583,
3989,
7170,
6275,
12,
12296,
1769,
203,
3639,
2583,
24899,
2629,
4921,
1435,
1545,
384,
6388,
39,
1371,
2378,
63,
3576,
12021,
6487,
315,
510,
737,
316,
27367,
2378,
8863,
203,
203,
3639,
1430,
384,
6388,
1190,
9446,
8579,
13937,
63,
3576,
12021,
15533,
203,
3639,
1430,
384,
6388,
39,
1371,
2378,
63,
3576,
12021,
15533,
203,
3639,
389,
13866,
12,
457,
84,
1345,
16,
1234,
12021,
16,
11013,
1769,
203,
203,
3639,
3626,
3423,
9446,
82,
12,
3576,
12021,
16,
11013,
18,
869,
5487,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* Original work Copyright 2016 Smart Contract Solutions, Inc.
* Modified work Copyright 2018 SECURRENCY INC.
*/
pragma solidity ^0.5.0;
/**
* @title SafeMath8
* @dev Math operations with safety checks that throw on error
*/
library SafeMath8 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint8 _a, uint8 _b) internal pure returns (uint8 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint8 _a, uint8 _b) internal pure returns (uint8) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint8 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(uint8 _a, uint8 _b) internal pure returns (uint8) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint8 _a, uint8 _b) internal pure returns (uint8 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
| * @dev Multiplies two numbers, throws on overflow./ Gas optimization: this is cheaper than asserting 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-solidity/pull/522 | function mul(uint8 _a, uint8 _b) internal pure returns (uint8 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
| 12,905,237 | [
1,
5002,
5259,
2795,
5600,
16,
1216,
603,
9391,
18,
19,
31849,
14850,
30,
333,
353,
19315,
7294,
2353,
1815,
310,
296,
69,
11,
486,
3832,
3634,
16,
1496,
326,
27641,
7216,
353,
13557,
309,
296,
70,
11,
353,
2546,
18432,
18,
2164,
30,
2333,
30,
6662,
18,
832,
19,
3678,
62,
881,
84,
292,
267,
19,
3190,
94,
881,
84,
292,
267,
17,
30205,
560,
19,
13469,
19,
25,
3787,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
14064,
12,
11890,
28,
389,
69,
16,
2254,
28,
389,
70,
13,
2713,
16618,
1135,
261,
11890,
28,
276,
13,
288,
203,
565,
309,
261,
67,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
203,
565,
276,
273,
389,
69,
380,
389,
70,
31,
203,
565,
1815,
12,
71,
342,
389,
69,
422,
389,
70,
1769,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';
import './ERC721Upgradeable.sol';
interface IHonorToken {
function updateBalance(
address wallet,
uint256 debit,
uint256 credit
) external;
function mint(address wallet, uint256 amount) external;
function burn(address wallet, uint256 amount) external;
function balanceOf(address wallet) external view returns (uint256);
}
/***
* .oooooo..o ooooo ooooo .o. oooooooooo. .oooooo. oooooo oooooo oooo
* d8P' `Y8 `888' `888' .888. `888' `Y8b d8P' `Y8b `888. `888. .8'
* Y88bo. 888 888 .8"888. 888 888 888 888 `888. .8888. .8'
* `"Y8888o. 888ooooo888 .8' `888. 888 888 888 888 `888 .8'`888. .8'
* `"Y88b 888 888 .88ooo8888. 888 888 888 888 `888.8' `888.8'
* oo .d8P 888 888 .8' `888. 888 d88' `88b d88' `888' `888'
* 8""88888P' o888o o888o o88o o8888o o888bood8P' `Y8bood8P' `8' `8'
*
*
*
* .oooooo. ooooo ooo oooooooooooo .oooooo..o ooooooooooooo
* d8P' `Y8b `888' `8' `888' `8 d8P' `Y8 8' 888 `8
* 888 888 888 8 888 Y88bo. 888
* 888 888 888 8 888oooo8 `"Y8888o. 888
* 888 888 888 8 888 " `"Y88b 888
* `88b d88b `88. .8' 888 o oo .d8P 888
* `Y8bood8P'Ybd' `YbodP' o888ooooood8 8""88888P' o888o
*
*
*
*/
contract ShadowQuest is OwnableUpgradeable, ERC721Upgradeable {
event Move(
address indexed owner,
uint256 indexed tokenId,
uint256 indexed direction
);
event LocationChanged(
uint8 indexed locationIdFrom,
uint8 indexed locationIdTo,
uint256 amount
);
uint256 public constant MAX_GEN0_SUPPLY = 9996;
uint256 public constant MAX_GEN1_SUPPLY = 18000;
uint256 public constant SALE_PRIVATE_PRICE = 0.075 ether;
uint256 public constant SALE_PUBLIC_PRICE = 0.08 ether;
uint256 public SALE_PUBLIC_STARTED_AT;
uint256 public SALE_PRIVATE_STARTED_AT;
uint256 public SALE_PRIVATE_MAX_SUPPLY;
uint256 public gen0Supply;
uint256 public gen1Supply;
string public provenanceHash;
IHonorToken public honorContract;
address private _proxyRegistryAddress;
address private _verifier;
string private _baseTokenURI;
struct TokenMeta {
address owner;
uint32 movedAt;
uint8 location;
uint56 meta;
}
mapping(uint256 => TokenMeta) public tokenState;
uint256[] internal _tokenStateKeys;
mapping(address => uint16) public _tokenOwnerState;
mapping(address => int16) private _balances;
uint256 public locationsBalance;
uint256[] public samsarIds;
mapping(address => uint256) public honrDeposited;
mapping(address => uint256) public honrWithdrawn;
function initialize(address verifier_, address proxyRegistryAddress_)
public
initializer
{
__ERC721_init('ShadowQuest', 'SQ');
__Ownable_init();
_verifier = verifier_;
_proxyRegistryAddress = proxyRegistryAddress_;
SALE_PRIVATE_MAX_SUPPLY = 3000;
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender() internal view override returns (address sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
function isOnArena(uint256 tokenId) internal view returns (bool) {
return tokenState[tokenId].location > 0;
}
function actualOwnerOf(uint256 tokenId) public view returns (address) {
if (tokenState[tokenId].owner != address(0)) {
return tokenState[tokenId].owner;
}
address tokenIdOwner = address(uint160(tokenId));
uint16 tokenIndex = uint16(tokenId >> 160);
require(_tokenOwnerState[tokenIdOwner] != 0, 'SQ: not minted');
require(
tokenIndex < _tokenOwnerState[tokenIdOwner],
'SQ: invalid index'
);
return tokenIdOwner;
}
/**
* @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'
);
if (owner_ == address(this)) {
return locationsBalance;
}
return uint16(int16(_tokenOwnerState[owner_]) + _balances[owner_]);
}
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
if (isOnArena(tokenId)) {
return address(this);
}
return actualOwnerOf(tokenId);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId)
internal
view
virtual
override
returns (bool)
{
if (tokenState[tokenId].owner != address(0)) {
return true;
}
address tokenIdOwner = address(uint160(tokenId));
uint16 tokenIndex = uint16(tokenId >> 160);
return
(_tokenOwnerState[tokenIdOwner] != 0) &&
(tokenIndex < _tokenOwnerState[tokenIdOwner]);
}
/**
* @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 override {
require(
ownerOf(tokenId) == from,
'ERC721: transfer from incorrect owner'
);
require(to != address(0), 'ERC721: transfer to the zero address');
require(to != from, "ERC721: can't transfer themself");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
if (tokenState[tokenId].owner == address(0)) {
_tokenStateKeys.push(tokenId);
}
_balances[from] -= 1;
_balances[to] += 1;
tokenState[tokenId].owner = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
function _recoverSigner(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
return
ECDSAUpgradeable.recover(
ECDSAUpgradeable.toEthSignedMessageHash(hash),
signature
);
}
function random(uint256 nonce, uint256 number)
internal
view
returns (uint256)
{
return
uint256(
keccak256(
abi.encodePacked(block.timestamp, block.difficulty, nonce)
)
) % (number + 1);
}
event MintGen1(
address indexed owner,
uint256 indexed nonce,
uint16 mintedAmount
);
event Steal(
address indexed owner,
address indexed samsarOwner,
uint256 indexed samsarId,
uint256 tokenId
);
function mintGen1(
uint16 expectedAmount,
uint256[] calldata samsarIds_,
uint256 nonce,
uint256 timestamp,
bytes memory sig
) external {
address sender = _msgSender();
uint16 tokenAmount = _tokenOwnerState[sender];
uint256 amount = expectedAmount - tokenAmount;
require(
amount > 0 && amount <= 10 && samsarIds_.length == amount,
'SQ: invalid amount'
);
require(
gen1Supply + amount < MAX_GEN1_SUPPLY,
'SQ: gen1 supply exceeded'
);
require(block.timestamp < timestamp, 'SQ: outdated transaction');
bytes32 hash = keccak256(
abi.encodePacked(
sender,
expectedAmount,
samsarIds_,
nonce,
timestamp
)
);
require(
_verifier == _recoverSigner(hash, sig),
'SQ: invalid signature'
);
gen1Supply += amount;
uint256 rand = random(nonce, 11 - amount);
if (rand <= amount - 1) {
address samsarOwner = actualOwnerOf(samsarIds_[rand]);
uint256 tokenId = uint256(uint160(samsarOwner)) |
(uint256(_tokenOwnerState[samsarOwner]) << 160);
_tokenOwnerState[samsarOwner] += 1;
amount -= 1;
emit Transfer(address(0), samsarOwner, tokenId);
emit Steal(sender, samsarOwner, samsarIds_[rand], tokenId);
}
uint256 ownerBase = uint256(uint160(sender));
uint16 minted;
for (uint256 index; index < amount; index++) {
emit Transfer(
address(0),
sender,
ownerBase | (uint256(_tokenOwnerState[sender] + minted) << 160)
);
minted += 1;
}
emit MintGen1(sender, nonce, minted);
if (minted > 0) {
_tokenOwnerState[sender] += minted;
}
}
function move(
uint8 locationIdFrom,
uint8 locationIdTo,
uint256[] calldata tokenIds,
/**
* nation, notIterable, samsarNotIterable
*/
uint256[] calldata tokenMeta,
uint256 timestamp,
bytes memory sig
) external {
require(block.timestamp < timestamp, 'SQ: outdated transaction');
address sender = _msgSender();
bytes32 hash = keccak256(
abi.encodePacked(
sender,
locationIdFrom,
locationIdTo,
tokenIds,
tokenMeta,
timestamp
)
);
require(
_verifier == _recoverSigner(hash, sig),
'SQ: invalid signature'
);
for (uint256 index; index < tokenIds.length; index++) {
uint256 tokenId = tokenIds[index];
require(
actualOwnerOf(tokenId) == sender,
'SQ: not owner of the token'
);
TokenMeta storage _tokenMeta = tokenState[tokenId];
require(
_tokenMeta.location == locationIdFrom,
'SQ: incorrect location'
);
if (uint8(tokenMeta[index] >> 8) == 1) {
_tokenStateKeys.push(tokenId);
}
if (uint8(tokenMeta[index] >> 16) == 1) {
samsarIds.push(tokenId);
}
tokenState[tokenId] = TokenMeta({
owner: sender,
movedAt: uint32(block.timestamp),
location: locationIdTo,
meta: uint8(tokenMeta[index])
});
if (locationIdTo == 0) {
emit Transfer(address(this), sender, tokenId);
} else if (locationIdFrom == 0) {
emit Transfer(sender, address(this), tokenId);
}
}
uint256 tokensAmount = tokenIds.length;
if (locationIdFrom == 0) {
locationsBalance += tokensAmount;
} else if (locationIdTo == 0) {
locationsBalance -= tokensAmount;
}
emit LocationChanged(locationIdFrom, locationIdTo, tokensAmount);
}
event HonrWithdraw(
address indexed wallet,
uint256 indexed nonce,
uint256 amount
);
function honrWithdraw(
uint256 amount,
uint256 expectedAmount,
uint256 nonce,
uint256 timestamp,
bytes memory sig
) external {
address sender = _msgSender();
bytes32 hash = keccak256(
abi.encodePacked(sender, amount, expectedAmount, nonce, timestamp)
);
require(
_verifier == _recoverSigner(hash, sig),
'SQ: invalid signature'
);
require(
honrWithdrawn[sender] + amount == expectedAmount,
'SQ: invalid transaction'
);
honorContract.mint(sender, amount);
honrWithdrawn[sender] += amount;
emit HonrWithdraw(sender, nonce, amount);
}
event HonrDeposit(address indexed wallet, uint256 amount);
function honrDeposit(
uint256 amount,
uint256 timestamp,
bytes memory sig
) external {
address sender = _msgSender();
bytes32 hash = keccak256(abi.encodePacked(sender, amount, timestamp));
require(
_verifier == _recoverSigner(hash, sig),
'SQ: invalid signature'
);
honorContract.burn(sender, amount);
honrDeposited[sender] += amount;
emit HonrDeposit(sender, amount);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner_, address operator_)
public
view
override
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner_)) == operator_) {
return true;
}
return super.isApprovedForAll(owner_, operator_);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return gen0Supply + gen1Supply - locationsBalance;
}
struct TokenData {
address owner;
uint8 location;
uint32 movedAt;
uint56 meta;
uint256 tokenId;
}
function sliceTokenStateArray(
TokenData[] memory arr,
uint256 start,
uint256 length
) internal pure returns (TokenData[] memory) {
TokenData[] memory result = new TokenData[](length);
for (uint256 index; index < length; index++) {
result[index] = arr[start + index];
}
return result;
}
function getSamsarTokens() external view returns (uint256[] memory) {
return samsarIds;
}
function getTokenStateKeys() external view returns (uint256[] memory) {
return _tokenStateKeys;
}
/**
* @dev location_ == -1 – any location
*/
function getOwnerTokens(address owner_, int8 location_)
public
view
returns (TokenData[] memory)
{
require(
owner_ != address(0),
'ERC721: balance query for the zero address'
);
uint256 balance = balanceOf(owner_);
TokenData[] memory ownedTokens = new TokenData[](balance);
uint256 ownerBase = uint256(uint160(owner_));
uint256 mintedAmount = _tokenOwnerState[owner_];
uint256 resultIndex;
for (uint256 index; index < mintedAmount; index++) {
uint256 tokenId = ownerBase | (index << 160);
TokenMeta storage currentTokenState = tokenState[tokenId];
if (
currentTokenState.owner == address(0) &&
(location_ == -1 || location_ == 0)
) {
ownedTokens[resultIndex++] = TokenData({
owner: currentTokenState.owner,
location: currentTokenState.location,
movedAt: currentTokenState.movedAt,
meta: currentTokenState.meta,
tokenId: tokenId
});
} else if (currentTokenState.owner == owner_) {
if (
location_ == -1 ||
uint8(location_) == currentTokenState.location
) {
ownedTokens[resultIndex++] = TokenData({
owner: currentTokenState.owner,
location: currentTokenState.location,
movedAt: currentTokenState.movedAt,
meta: currentTokenState.meta,
tokenId: tokenId
});
}
}
}
for (uint256 index = 0; index < _tokenStateKeys.length; index++) {
if (resultIndex == balance) {
break;
}
uint256 tokenId = _tokenStateKeys[index];
if (tokenState[tokenId].owner != owner_) {
continue;
}
address tokenIdOwner = address(uint160(tokenId));
if (tokenIdOwner == owner_) {
continue;
}
if (
location_ == -1 ||
tokenState[tokenId].location == uint8(location_)
) {
TokenMeta storage currentTokenState = tokenState[tokenId];
ownedTokens[resultIndex++] = TokenData({
owner: currentTokenState.owner,
location: currentTokenState.location,
movedAt: currentTokenState.movedAt,
meta: currentTokenState.meta,
tokenId: tokenId
});
}
}
return sliceTokenStateArray(ownedTokens, 0, resultIndex);
}
/* OwnerOnly */
function setVerifier(address verifier_) external onlyOwner {
_verifier = verifier_;
}
function setBaseURI(string memory baseURI_) external onlyOwner {
_baseTokenURI = baseURI_;
}
function setState(
bool publicSaleState_,
bool privateSaleState_,
uint256 maxPresaleSupply_
) external onlyOwner {
SALE_PUBLIC_STARTED_AT = publicSaleState_ ? block.timestamp : 0;
SALE_PRIVATE_STARTED_AT = privateSaleState_ ? block.timestamp : 0;
SALE_PRIVATE_MAX_SUPPLY = maxPresaleSupply_;
}
function withdraw(uint256 amount) public onlyOwner {
(bool success, ) = _msgSender().call{value: amount}('');
require(success, 'Withdraw failed');
}
function withdrawAll() external onlyOwner {
withdraw(address(this).balance);
}
function setHonorContract(IHonorToken honorContract_) external onlyOwner {
honorContract = honorContract_;
}
function setLocationsBalance(uint256 amount) external onlyOwner {
locationsBalance = amount;
}
function pushTokenStateKeys(uint256[] calldata tokenIds)
external
onlyOwner
{
uint256 tokensAmount = tokenIds.length;
for (uint256 index; index < tokensAmount; index++) {
_tokenStateKeys.push(tokenIds[index]);
}
}
function _mintGen0(address sender, uint16 amount) internal {
require(
gen0Supply + amount <= MAX_GEN0_SUPPLY,
'SQ: gen0 supply overflow'
);
uint16 tokensAmount = _tokenOwnerState[sender] + amount;
uint256 ownerBase = uint256(uint160(sender));
for (
uint256 index = _tokenOwnerState[sender];
index < tokensAmount;
index++
) {
emit Transfer(address(0), sender, ownerBase | (index << 160));
}
_tokenOwnerState[sender] = tokensAmount;
gen0Supply += amount;
}
function mintReserved(address wallet, uint16 amount) external onlyOwner {
address receiver = wallet == address(0) ? _msgSender() : wallet;
_mintGen0(receiver, amount);
}
function revertFalseMint(address wallet, uint16 amount) external onlyOwner {
gen1Supply -= amount;
_tokenOwnerState[wallet] -= amount;
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// 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 (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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol';
import '@openzeppelin/contracts-upgradeable/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 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
{
__Context_init_unchained();
__ERC165_init_unchained();
__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(false, 'Implementation required');
return 0;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(false, 'Implementation required');
return address(0);
}
/**
* @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 overridden 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 = 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) {
require(false, 'Implementation required');
return false;
}
/**
* @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 = 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 {}
/**
* @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 {}
/**
* @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 {}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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 {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 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);
} | * @dev See {IERC721Enumerable-totalSupply}./ | function totalSupply() public view virtual returns (uint256) {
return gen0Supply + gen1Supply - locationsBalance;
}
| 121,045 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
3572,
25121,
17,
4963,
3088,
1283,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
3157,
20,
3088,
1283,
397,
3157,
21,
3088,
1283,
300,
7838,
13937,
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
] |
./partial_match/1/0x59FAB9bF88544F86aBAe89059650967e5dFa5c9c/sources/Papayahub.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;
mapping(address => bool) public isMultiOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
addMultiOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
modifier onlyMultiOwner() {
require(isMultiOwner[_msgSender()], "Caller is not a multi-owner");
_;
}
function addMultiOwner(address newMultiOwner) public onlyOwner {
require(!isMultiOwner[newMultiOwner], "Already a multi-owner");
isMultiOwner[newMultiOwner] = true;
}
function removeMultiOwner(address multiOwnerToRemove) public onlyOwner {
require(isMultiOwner[multiOwnerToRemove], "Not a multi-owner");
isMultiOwner[multiOwnerToRemove] = false;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
}
| 15,685,973 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
25129,
5541,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
13866,
5460,
12565,
24899,
3576,
12021,
10663,
203,
3639,
527,
5002,
5541,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5002,
5541,
1435,
288,
203,
3639,
2583,
12,
291,
5002,
5541,
63,
67,
3576,
12021,
1435,
6487,
315,
11095,
353,
486,
279,
3309,
17,
8443,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
527,
5002,
5541,
12,
2867,
394,
5002,
5541,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
5,
291,
5002,
5541,
63,
2704,
5002,
5541,
6487,
315,
9430,
279,
3309,
17,
8443,
8863,
203,
3639,
25129,
5541,
63,
2704,
5002,
5541,
65,
273,
638,
31,
203,
565,
289,
203,
203,
565,
445,
1206,
5002,
5541,
12,
2867,
3309,
5541,
12765,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
291,
5002,
5541,
63,
7027,
5541,
12765,
6487,
315,
1248,
2
] |
pragma solidity 0.4.26;
// import "./OraclizeAPI.sol"; // MAINNET
import "../test/OraclizeAPITesting.sol"; // TESTING
import "../Oracle.sol";
import "../WETH.sol";
/**
* @title Atomic Loans Oraclize Contract
* @author Atomic Loans
*/
contract Oraclize is usingOraclize, Oracle {
WETH weth;
MedianizerInterface medm;
uint256 public gasLimit = 200000;
event Update(uint128 payment_, ERC20 token_);
event __Callback(bytes32 queryId, string result_);
/**
* @notice Construct a new Oraclize Oracle
* @param med_ The address of the Medianizer
* @param medm_ The address of the MakerDAO Medianizer
* @param weth_ The WETH token address
*/
constructor(MedianizerInterface med_, MedianizerInterface medm_, WETH weth_) public {
require(address(med_) != address(0), "Oraclize.constructor: med_ is zero address");
require(address(medm_) != address(0), "Oraclize.constructor: medm_ is zero address");
require(address(weth_) != address(0), "Oraclize.constructor: weth_ is zero address");
med = med_;
medm = medm_;
weth = weth_;
oraclize_setProof(proofType_Android | proofStorage_IPFS);
}
function () public payable { }
/**
* @notice Gets the payment needed to update the Oracle
* @return Oraclize price for query in wei
*/
function bill() public view returns (uint256) {
return oraclize_getPrice("URL", gasLimit);
}
/**
* @notice Sender redeems WETH in exchange for Updating the Oracle and receiving stablecoin tokens
* @param payment_ The amount of WETH used as payment for Oraclize
* @param token_ The address of the ERC20 stablecoin to receive as a reward
*/
function update(uint128 payment_, ERC20 token_) public {
require(uint32(now) > timeout, "Oraclize.update: now is less than timeout");
require(payment_ == oraclize_getPrice("URL", gasLimit), "Oraclize.update: payment doesn't equal oraclize_getPrice");
require(weth.transferFrom(msg.sender, address(this), uint(payment_)), "Oraclize.update: failed to transfer weth from msg.sender");
bytes32 queryId = getAssetPrice(payment_);
setPaymentTokenPrice(queryId, uint128(medm.read()));
asyncRequests[queryId].rewardee = msg.sender;
asyncRequests[queryId].payment = payment_;
asyncRequests[queryId].token = token_;
timeout = uint32(now) + DELAY;
emit Update(payment_, token_);
}
/**
* @notice Creates request for Oraclize to get the BTC price
*/
function getAssetPrice(uint128) internal returns (bytes32);
/**
* @notice Oraclize returns result from API price query
* @param queryId ID of the query from Oraclize
* @param result_ API price returned from Oraclize query
*/
function __callback(bytes32 queryId, string result_, bytes) public {
require(msg.sender == oraclize_cbAddress(), "Oraclize.__callback: msg.sender isn't Oraclize address");
require(asyncRequests[queryId].rewardee != address(0), "Oraclize.__callback: rewardee is not zero address");
uint128 res = uint128(parseInt(result_, 18));
setAssetPrice(queryId, res, uint32(now + 43200));
emit __Callback(queryId, result_);
}
/**
* @notice Sets Max Reward for Chainlink Contracts
*/
function setMaxReward(uint256) public {
require(msg.sender == address(med), "Oraclize.setMaxReward: msg.sender isn't medianizer address");
}
/**
* @notice Sets Gas Limit for Oraclize Contracts
* @param gasLimit_ Gas Limit that Oraclize will use when updating the contracts
*/
function setGasLimit(uint256 gasLimit_) public {
require(msg.sender == address(med), "Oraclize.setGasLimit: msg.sender isn't medianizer address");
gasLimit = gasLimit_;
}
}
| * @title Atomic Loans Oraclize Contract @author Atomic Loans/ | contract Oraclize is usingOraclize, Oracle {
WETH weth;
MedianizerInterface medm;
uint256 public gasLimit = 200000;
event Update(uint128 payment_, ERC20 token_);
event __Callback(bytes32 queryId, string result_);
import "../Oracle.sol";
constructor(MedianizerInterface med_, MedianizerInterface medm_, WETH weth_) public {
require(address(med_) != address(0), "Oraclize.constructor: med_ is zero address");
require(address(medm_) != address(0), "Oraclize.constructor: medm_ is zero address");
require(address(weth_) != address(0), "Oraclize.constructor: weth_ is zero address");
med = med_;
medm = medm_;
weth = weth_;
oraclize_setProof(proofType_Android | proofStorage_IPFS);
}
function () public payable { }
function bill() public view returns (uint256) {
return oraclize_getPrice("URL", gasLimit);
}
function update(uint128 payment_, ERC20 token_) public {
require(uint32(now) > timeout, "Oraclize.update: now is less than timeout");
require(payment_ == oraclize_getPrice("URL", gasLimit), "Oraclize.update: payment doesn't equal oraclize_getPrice");
require(weth.transferFrom(msg.sender, address(this), uint(payment_)), "Oraclize.update: failed to transfer weth from msg.sender");
bytes32 queryId = getAssetPrice(payment_);
setPaymentTokenPrice(queryId, uint128(medm.read()));
asyncRequests[queryId].rewardee = msg.sender;
asyncRequests[queryId].payment = payment_;
asyncRequests[queryId].token = token_;
timeout = uint32(now) + DELAY;
emit Update(payment_, token_);
}
function getAssetPrice(uint128) internal returns (bytes32);
function __callback(bytes32 queryId, string result_, bytes) public {
require(msg.sender == oraclize_cbAddress(), "Oraclize.__callback: msg.sender isn't Oraclize address");
require(asyncRequests[queryId].rewardee != address(0), "Oraclize.__callback: rewardee is not zero address");
uint128 res = uint128(parseInt(result_, 18));
setAssetPrice(queryId, res, uint32(now + 43200));
emit __Callback(queryId, result_);
}
function setMaxReward(uint256) public {
require(msg.sender == address(med), "Oraclize.setMaxReward: msg.sender isn't medianizer address");
}
function setGasLimit(uint256 gasLimit_) public {
require(msg.sender == address(med), "Oraclize.setGasLimit: msg.sender isn't medianizer address");
gasLimit = gasLimit_;
}
}
| 14,079,868 | [
1,
23102,
3176,
634,
531,
354,
830,
554,
13456,
225,
11553,
3176,
634,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
531,
354,
830,
554,
353,
1450,
51,
354,
830,
554,
16,
28544,
288,
203,
565,
678,
1584,
44,
341,
546,
31,
203,
565,
20158,
2779,
1824,
1358,
6735,
81,
31,
203,
203,
565,
2254,
5034,
1071,
16189,
3039,
273,
576,
11706,
31,
203,
203,
565,
871,
2315,
12,
11890,
10392,
5184,
67,
16,
4232,
39,
3462,
1147,
67,
1769,
203,
203,
565,
871,
1001,
2428,
12,
3890,
1578,
843,
548,
16,
533,
563,
67,
1769,
203,
203,
5666,
315,
6216,
23601,
18,
18281,
14432,
203,
565,
3885,
12,
13265,
2779,
1824,
1358,
6735,
67,
16,
20158,
2779,
1824,
1358,
6735,
81,
67,
16,
678,
1584,
44,
341,
546,
67,
13,
1071,
288,
203,
3639,
2583,
12,
2867,
12,
2937,
67,
13,
480,
1758,
12,
20,
3631,
315,
51,
354,
830,
554,
18,
12316,
30,
6735,
67,
353,
3634,
1758,
8863,
203,
3639,
2583,
12,
2867,
12,
2937,
81,
67,
13,
480,
1758,
12,
20,
3631,
315,
51,
354,
830,
554,
18,
12316,
30,
6735,
81,
67,
353,
3634,
1758,
8863,
203,
3639,
2583,
12,
2867,
12,
91,
546,
67,
13,
480,
1758,
12,
20,
3631,
315,
51,
354,
830,
554,
18,
12316,
30,
341,
546,
67,
353,
3634,
1758,
8863,
203,
3639,
6735,
273,
6735,
67,
31,
203,
3639,
6735,
81,
273,
6735,
81,
67,
31,
203,
3639,
341,
546,
273,
341,
546,
67,
31,
203,
3639,
578,
10150,
554,
67,
542,
20439,
12,
24207,
559,
67,
19095,
571,
14601,
3245,
67,
2579,
4931,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2
] |
// SPDX-License-Identifier: UNLICENSED
// The BentoBox
// ▄▄▄▄· ▄▄▄ . ▐ ▄ ▄▄▄▄▄ ▄▄▄▄· ▐▄• ▄
// ▐█ ▀█▪▀▄.▀·█▌▐█•██ ▪ ▐█ ▀█▪▪ █▌█▌▪
// ▐█▀▀█▄▐▀▀▪▄▐█▐▐▌ ▐█.▪ ▄█▀▄ ▐█▀▀█▄ ▄█▀▄ ·██·
// ██▄▪▐█▐█▄▄▌██▐█▌ ▐█▌·▐█▌.▐▌██▄▪▐█▐█▌.▐▌▪▐█·█▌
// ·▀▀▀▀ ▀▀▀ ▀▀ █▪ ▀▀▀ ▀█▄▀▪·▀▀▀▀ ▀█▄▀▪•▀▀ ▀▀
// This contract stores funds, handles their transfers, supports flash loans and strategies.
// Copyright (c) 2021 BoringCrypto - All rights reserved
// Twitter: @Boring_Crypto
// Special thanks to Keno for all his hard work and support
// Version 22-Mar-2021
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// solhint-disable avoid-low-level-calls
// solhint-disable not-rely-on-time
// solhint-disable no-inline-assembly
// File @boringcrypto/boring-solidity/contracts/interfaces/[email protected]
// License-Identifier: MIT
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
);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function decimals() external view returns (uint256);
}
// File contracts/interfaces/IFlashLoan.sol
// License-Identifier: MIT
interface IFlashBorrower {
/// @notice The flashloan callback. `amount` + `fee` needs to repayed to msg.sender before this call returns.
/// @param sender The address of the invoker of this flashloan.
/// @param token The address of the token that is loaned.
/// @param amount of the `token` that is loaned.
/// @param fee The fee that needs to be paid on top for this loan. Needs to be the same as `token`.
/// @param data Additional data that was passed to the flashloan function.
function onFlashLoan(
address sender,
IERC20 token,
uint256 amount,
uint256 fee,
bytes calldata data
) external;
}
interface IBatchFlashBorrower {
/// @notice The callback for batched flashloans. Every amount + fee needs to repayed to msg.sender before this call returns.
/// @param sender The address of the invoker of this flashloan.
/// @param tokens Array of addresses for ERC-20 tokens that is loaned.
/// @param amounts A one-to-one map to `tokens` that is loaned.
/// @param fees A one-to-one map to `tokens` that needs to be paid on top for each loan. Needs to be the same token.
/// @param data Additional data that was passed to the flashloan function.
function onBatchFlashLoan(
address sender,
IERC20[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata fees,
bytes calldata data
) external;
}
// File contracts/interfaces/IWETH.sol
// License-Identifier: MIT
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// File contracts/interfaces/IStrategy.sol
// License-Identifier: MIT
interface IStrategy {
/// @notice Send the assets to the Strategy and call skim to invest them.
/// @param amount The amount of tokens to invest.
function skim(uint256 amount) external;
/// @notice Harvest any profits made converted to the asset and pass them to the caller.
/// @param balance The amount of tokens the caller thinks it has invested.
/// @param sender The address of the initiator of this transaction. Can be used for reimbursements, etc.
/// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`.
function harvest(uint256 balance, address sender)
external
returns (int256 amountAdded);
/// @notice Withdraw assets. The returned amount can differ from the requested amount due to rounding.
/// @dev The `actualAmount` should be very close to the amount.
/// The difference should NOT be used to report a loss. That's what harvest is for.
/// @param amount The requested amount the caller wants to withdraw.
/// @return actualAmount The real amount that is withdrawn.
function withdraw(uint256 amount) external returns (uint256 actualAmount);
/// @notice Withdraw all assets in the safest way possible. This shouldn't fail.
/// @param balance The amount of tokens the caller thinks it has invested.
/// @return amountAdded The delta (+profit or -loss) that occured in contrast to `balance`.
function exit(uint256 balance) external returns (int256 amountAdded);
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
// License-Identifier: MIT
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(SIG_TRANSFER, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"BoringERC20: Transfer failed"
);
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"BoringERC20: TransferFrom failed"
);
}
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
// License-Identifier: MIT
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
// License-Identifier: MIT
struct Rebase {
uint128 elastic;
uint128 base;
}
/// @notice A rebasing library using overflow-/underflow-safe math.
library RebaseLibrary {
using BoringMath for uint256;
using BoringMath128 for uint128;
/// @notice Calculates the base value in relationship to `elastic` and `total`.
function toBase(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (uint256 base) {
if (total.elastic == 0) {
base = elastic;
} else {
base = elastic.mul(total.base) / total.elastic;
if (roundUp && base.mul(total.elastic) / total.base < elastic) {
base = base.add(1);
}
}
}
/// @notice Calculates the elastic value in relationship to `base` and `total`.
function toElastic(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (uint256 elastic) {
if (total.base == 0) {
elastic = base;
} else {
elastic = base.mul(total.elastic) / total.base;
if (roundUp && elastic.mul(total.base) / total.elastic < base) {
elastic = elastic.add(1);
}
}
}
/// @notice Add `elastic` to `total` and doubles `total.base`.
/// @return (Rebase) The new total.
/// @return base in relationship to `elastic`.
function add(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (Rebase memory, uint256 base) {
base = toBase(total, elastic, roundUp);
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return (total, base);
}
/// @notice Sub `base` from `total` and update `total.elastic`.
/// @return (Rebase) The new total.
/// @return elastic in relationship to `base`.
function sub(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (Rebase memory, uint256 elastic) {
elastic = toElastic(total, base, roundUp);
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return (total, elastic);
}
/// @notice Add `elastic` and `base` to `total`.
function add(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return total;
}
/// @notice Subtract `elastic` and `base` to `total`.
function sub(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return total;
}
/// @notice Add `elastic` to `total` and update storage.
/// @return newElastic Returns updated `elastic`.
function addElastic(Rebase storage total, uint256 elastic)
internal
returns (uint256 newElastic)
{
newElastic = total.elastic = total.elastic.add(elastic.to128());
}
/// @notice Subtract `elastic` from `total` and update storage.
/// @return newElastic Returns updated `elastic`.
function subElastic(Rebase storage total, uint256 elastic)
internal
returns (uint256 newElastic)
{
newElastic = total.elastic = total.elastic.sub(elastic.to128());
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
// License-Identifier: MIT
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol
// Edited by BoringCrypto
contract BoringOwnableData {
address public owner;
address public pendingOwner;
}
contract BoringOwnable is BoringOwnableData {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @notice `owner` defaults to msg.sender on construction.
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) public onlyOwner {
if (direct) {
// Checks
require(
newOwner != address(0) || renounce,
"Ownable: zero address"
);
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
}
/// @notice Needs to be called by `pendingOwner` to claim ownership.
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(
msg.sender == _pendingOwner,
"Ownable: caller != pending owner"
);
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
/// @notice Only allows the `owner` to execute the function.
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
}
// File @boringcrypto/boring-solidity/contracts/interfaces/[email protected]
// License-Identifier: MIT
interface IMasterContract {
/// @notice Init function that gets called from `BoringFactory.deploy`.
/// Also kown as the constructor for cloned contracts.
/// Any ETH send to `BoringFactory.deploy` ends up here.
/// @param data Can be abi encoded arguments or anything else.
function init(bytes calldata data) external payable;
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
// License-Identifier: MIT
contract BoringFactory {
event LogDeploy(
address indexed masterContract,
bytes data,
address indexed cloneAddress
);
/// @notice Mapping from clone contracts to their masterContract.
mapping(address => address) public masterContractOf;
/// @notice Deploys a given master Contract as a clone.
/// Any ETH transferred with this call is forwarded to the new clone.
/// Emits `LogDeploy`.
/// @param masterContract The address of the contract to clone.
/// @param data Additional abi encoded calldata that is passed to the new clone via `IMasterContract.init`.
/// @param useCreate2 Creates the clone by using the CREATE2 opcode, in this case `data` will be used as salt.
/// @return cloneAddress Address of the created clone contract.
function deploy(
address masterContract,
bytes calldata data,
bool useCreate2
) public payable returns (address cloneAddress) {
require(
masterContract != address(0),
"BoringFactory: No masterContract"
);
bytes20 targetBytes = bytes20(masterContract); // Takes the first 20 bytes of the masterContract's address
if (useCreate2) {
// each masterContract has different code already. So clones are distinguished by their data only.
bytes32 salt = keccak256(data);
// Creates clone, more info here: https://blog.openzeppelin.com/deep-dive-into-the-minimal-proxy-contract/
assembly {
let clone := mload(0x40)
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone, 0x14), targetBytes)
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
cloneAddress := create2(0, clone, 0x37, salt)
}
} else {
assembly {
let clone := mload(0x40)
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone, 0x14), targetBytes)
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
cloneAddress := create(0, clone, 0x37)
}
}
masterContractOf[cloneAddress] = masterContract;
IMasterContract(cloneAddress).init{value: msg.value}(data);
emit LogDeploy(masterContract, data, cloneAddress);
}
}
// File contracts/MasterContractManager.sol
// License-Identifier: UNLICENSED
contract MasterContractManager is BoringOwnable, BoringFactory {
event LogWhiteListMasterContract(
address indexed masterContract,
bool approved
);
event LogSetMasterContractApproval(
address indexed masterContract,
address indexed user,
bool approved
);
event LogRegisterProtocol(address indexed protocol);
/// @notice masterContract to user to approval state
mapping(address => mapping(address => bool)) public masterContractApproved;
/// @notice masterContract to whitelisted state for approval without signed message
mapping(address => bool) public whitelistedMasterContracts;
/// @notice user nonces for masterContract approvals
mapping(address => uint256) public nonces;
bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH =
keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA =
"\x19\x01";
bytes32 private constant APPROVAL_SIGNATURE_HASH =
keccak256(
"SetMasterContractApproval(string warning,address user,address masterContract,bool approved,uint256 nonce)"
);
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _DOMAIN_SEPARATOR;
// solhint-disable-next-line var-name-mixedcase
uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;
constructor() public {
uint256 chainId;
assembly {
chainId := chainid()
}
_DOMAIN_SEPARATOR = _calculateDomainSeparator(
DOMAIN_SEPARATOR_CHAIN_ID = chainId
);
}
function _calculateDomainSeparator(uint256 chainId)
private
view
returns (bytes32)
{
return
keccak256(
abi.encode(
DOMAIN_SEPARATOR_SIGNATURE_HASH,
keccak256("BentoBox V1"),
chainId,
address(this)
)
);
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() public view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return
chainId == DOMAIN_SEPARATOR_CHAIN_ID
? _DOMAIN_SEPARATOR
: _calculateDomainSeparator(chainId);
}
/// @notice Other contracts need to register with this master contract so that users can approve them for the BentoBox.
function registerProtocol() public {
masterContractOf[msg.sender] = msg.sender;
emit LogRegisterProtocol(msg.sender);
}
/// @notice Enables or disables a contract for approval without signed message.
function whitelistMasterContract(address masterContract, bool approved)
public
onlyOwner
{
// Checks
require(masterContract != address(0), "MasterCMgr: Cannot approve 0");
// Effects
whitelistedMasterContracts[masterContract] = approved;
emit LogWhiteListMasterContract(masterContract, approved);
}
/// @notice Approves or revokes a `masterContract` access to `user` funds.
/// @param user The address of the user that approves or revokes access.
/// @param masterContract The address who gains or loses access.
/// @param approved If True approves access. If False revokes access.
/// @param v Part of the signature. (See EIP-191)
/// @param r Part of the signature. (See EIP-191)
/// @param s Part of the signature. (See EIP-191)
// F4 - Check behaviour for all function arguments when wrong or extreme
// F4: Don't allow masterContract 0 to be approved. Unknown contracts will have a masterContract of 0.
// F4: User can't be 0 for signed approvals because the recoveredAddress will be 0 if ecrecover fails
function setMasterContractApproval(
address user,
address masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
) public {
// Checks
require(masterContract != address(0), "MasterCMgr: masterC not set"); // Important for security
// If no signature is provided, the fallback is executed
if (r == 0 && s == 0 && v == 0) {
require(user == msg.sender, "MasterCMgr: user not sender");
require(
masterContractOf[user] == address(0),
"MasterCMgr: user is clone"
);
require(
whitelistedMasterContracts[masterContract],
"MasterCMgr: not whitelisted"
);
} else {
// Important for security - any address without masterContract has address(0) as masterContract
// So approving address(0) would approve every address, leading to full loss of funds
// Also, ecrecover returns address(0) on failure. So we check this:
require(user != address(0), "MasterCMgr: User cannot be 0");
// C10 - Protect signatures against replay, use nonce and chainId (SWC-121)
// C10: nonce + chainId are used to prevent replays
// C11 - All signatures strictly EIP-712 (SWC-117 SWC-122)
// C11: signature is EIP-712 compliant
// C12 - abi.encodePacked can't contain variable length user input (SWC-133)
// C12: abi.encodePacked has fixed length parameters
bytes32 digest = keccak256(
abi.encodePacked(
EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA,
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
APPROVAL_SIGNATURE_HASH,
approved
? keccak256(
"Give FULL access to funds in (and approved to) BentoBox?"
)
: keccak256("Revoke access to BentoBox?"),
user,
masterContract,
approved,
nonces[user]++
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress == user, "MasterCMgr: Invalid Signature");
}
// Effects
masterContractApproved[masterContract][user] = approved;
emit LogSetMasterContractApproval(masterContract, user, approved);
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
// License-Identifier: MIT
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData)
internal
pure
returns (string memory)
{
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
/// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
/// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail)
external
payable
returns (bool[] memory successes, bytes[] memory results)
{
successes = new bool[](calls.length);
results = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(
calls[i]
);
require(success || !revertOnFail, _getRevertMsg(result));
successes[i] = success;
results[i] = result;
}
}
}
contract BoringBatchable is BaseBoringBatchable {
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
// File contracts/BentoBox.sol
// License-Identifier: UNLICENSED
/// @title BentoBox
/// @author BoringCrypto, Keno
/// @notice The BentoBox is a vault for tokens. The stored tokens can be flash loaned and used in strategies.
/// Yield from this will go to the token depositors.
/// Rebasing tokens ARE NOT supported and WILL cause loss of funds.
/// Any funds transfered directly onto the BentoBox will be lost, use the deposit function instead.
contract BentoBoxV1 is MasterContractManager, BoringBatchable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using RebaseLibrary for Rebase;
// ************** //
// *** EVENTS *** //
// ************** //
event LogDeposit(
IERC20 indexed token,
address indexed from,
address indexed to,
uint256 amount,
uint256 share
);
event LogWithdraw(
IERC20 indexed token,
address indexed from,
address indexed to,
uint256 amount,
uint256 share
);
event LogTransfer(
IERC20 indexed token,
address indexed from,
address indexed to,
uint256 share
);
event LogFlashLoan(
address indexed borrower,
IERC20 indexed token,
uint256 amount,
uint256 feeAmount,
address indexed receiver
);
event LogStrategyTargetPercentage(
IERC20 indexed token,
uint256 targetPercentage
);
event LogStrategyQueued(IERC20 indexed token, IStrategy indexed strategy);
event LogStrategySet(IERC20 indexed token, IStrategy indexed strategy);
event LogStrategyInvest(IERC20 indexed token, uint256 amount);
event LogStrategyDivest(IERC20 indexed token, uint256 amount);
event LogStrategyProfit(IERC20 indexed token, uint256 amount);
event LogStrategyLoss(IERC20 indexed token, uint256 amount);
// *************** //
// *** STRUCTS *** //
// *************** //
struct StrategyData {
uint64 strategyStartDate;
uint64 targetPercentage;
uint128 balance; // the balance of the strategy that BentoBox thinks is in there
}
// ******************************** //
// *** CONSTANTS AND IMMUTABLES *** //
// ******************************** //
// V2 - Can they be private?
// V2: Private to save gas, to verify it's correct, check the constructor arguments
IERC20 private immutable wethToken;
IERC20 private constant USE_ETHEREUM = IERC20(0);
uint256 private constant FLASH_LOAN_FEE = 50; // 0.05%
uint256 private constant FLASH_LOAN_FEE_PRECISION = 1e5;
uint256 private constant STRATEGY_DELAY = 0 weeks;
uint256 private constant MAX_TARGET_PERCENTAGE = 95; // 95%
uint256 private constant MINIMUM_SHARE_BALANCE = 1000; // To prevent the ratio going off
// ***************** //
// *** VARIABLES *** //
// ***************** //
// Balance per token per address/contract in shares
mapping(IERC20 => mapping(address => uint256)) public balanceOf;
// Rebase from amount to share
mapping(IERC20 => Rebase) public totals;
mapping(IERC20 => IStrategy) public strategy;
mapping(IERC20 => IStrategy) public pendingStrategy;
mapping(IERC20 => StrategyData) public strategyData;
// ******************* //
// *** CONSTRUCTOR *** //
// ******************* //
constructor(IERC20 wethToken_) public {
wethToken = wethToken_;
}
// ***************** //
// *** MODIFIERS *** //
// ***************** //
/// Modifier to check if the msg.sender is allowed to use funds belonging to the 'from' address.
/// If 'from' is msg.sender, it's allowed.
/// If 'from' is the BentoBox itself, it's allowed. Any ETH, token balances (above the known balances) or BentoBox balances
/// can be taken by anyone.
/// This is to enable skimming, not just for deposits, but also for withdrawals or transfers, enabling better composability.
/// If 'from' is a clone of a masterContract AND the 'from' address has approved that masterContract, it's allowed.
modifier allowed(address from) {
if (from != msg.sender && from != address(this)) {
// From is sender or you are skimming
address masterContract = masterContractOf[msg.sender];
require(
masterContract != address(0),
"BentoBox: no masterContract"
);
require(
masterContractApproved[masterContract][from],
"BentoBox: Transfer not approved"
);
}
_;
}
// ************************** //
// *** INTERNAL FUNCTIONS *** //
// ************************** //
/// @dev Returns the total balance of `token` this contracts holds,
/// plus the total amount this contract thinks the strategy holds.
function _tokenBalanceOf(IERC20 token)
internal
view
returns (uint256 amount)
{
amount = token.balanceOf(address(this)).add(
strategyData[token].balance
);
}
// ************************ //
// *** PUBLIC FUNCTIONS *** //
// ************************ //
/// @dev Helper function to represent an `amount` of `token` in shares.
/// @param token The ERC-20 token.
/// @param amount The `token` amount.
/// @param roundUp If the result `share` should be rounded up.
/// @return share The token amount represented in shares.
function toShare(
IERC20 token,
uint256 amount,
bool roundUp
) external view returns (uint256 share) {
share = totals[token].toBase(amount, roundUp);
}
/// @dev Helper function represent shares back into the `token` amount.
/// @param token The ERC-20 token.
/// @param share The amount of shares.
/// @param roundUp If the result should be rounded up.
/// @return amount The share amount back into native representation.
function toAmount(
IERC20 token,
uint256 share,
bool roundUp
) external view returns (uint256 amount) {
amount = totals[token].toElastic(share, roundUp);
}
/// @notice Deposit an amount of `token` represented in either `amount` or `share`.
/// @param token_ The ERC-20 token to deposit.
/// @param from which account to pull the tokens.
/// @param to which account to push the tokens.
/// @param amount Token amount in native representation to deposit.
/// @param share Token amount represented in shares to deposit. Takes precedence over `amount`.
/// @return amountOut The amount deposited.
/// @return shareOut The deposited amount represented in shares.
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
)
public
payable
allowed(from)
returns (uint256 amountOut, uint256 shareOut)
{
// Checks
require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds
// Effects
IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_;
Rebase memory total = totals[token];
// If a new token gets added, the tokenSupply call checks that this is a deployed contract. Needed for security.
require(
total.elastic != 0 || token.totalSupply() > 0,
"BentoBox: No tokens"
);
if (share == 0) {
// value of the share may be lower than the amount due to rounding, that's ok
share = total.toBase(amount, false);
// Any deposit should lead to at least the minimum share balance, otherwise it's ignored (no amount taken)
if (total.base.add(share.to128()) < MINIMUM_SHARE_BALANCE) {
return (0, 0);
}
} else {
// amount may be lower than the value of share due to rounding, in that case, add 1 to amount (Always round up)
amount = total.toElastic(share, true);
}
// In case of skimming, check that only the skimmable amount is taken.
// For ETH, the full balance is available, so no need to check.
// During flashloans the _tokenBalanceOf is lower than 'reality', so skimming deposits will mostly fail during a flashloan.
require(
from != address(this) ||
token_ == USE_ETHEREUM ||
amount <= _tokenBalanceOf(token).sub(total.elastic),
"BentoBox: Skim too much"
);
balanceOf[token][to] = balanceOf[token][to].add(share);
total.base = total.base.add(share.to128());
total.elastic = total.elastic.add(amount.to128());
totals[token] = total;
// Interactions
// During the first deposit, we check that this token is 'real'
if (token_ == USE_ETHEREUM) {
// X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113)
// X2: If the WETH implementation is faulty or malicious, it will block adding ETH (but we know the WETH implementation)
IWETH(address(wethToken)).deposit{value: amount}();
} else if (from != address(this)) {
// X2 - If there is an error, could it cause a DoS. Like balanceOf causing revert. (SWC-113)
// X2: If the token implementation is faulty or malicious, it may block adding tokens. Good.
token.safeTransferFrom(from, address(this), amount);
}
emit LogDeposit(token, from, to, amount, share);
amountOut = amount;
shareOut = share;
}
/// @notice Withdraws an amount of `token` from a user account.
/// @param token_ The ERC-20 token to withdraw.
/// @param from which user to pull the tokens.
/// @param to which user to push the tokens.
/// @param amount of tokens. Either one of `amount` or `share` needs to be supplied.
/// @param share Like above, but `share` takes precedence over `amount`.
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) public allowed(from) returns (uint256 amountOut, uint256 shareOut) {
// Checks
require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds
// Effects
IERC20 token = token_ == USE_ETHEREUM ? wethToken : token_;
Rebase memory total = totals[token];
if (share == 0) {
// value of the share paid could be lower than the amount paid due to rounding, in that case, add a share (Always round up)
share = total.toBase(amount, true);
} else {
// amount may be lower than the value of share due to rounding, that's ok
amount = total.toElastic(share, false);
}
balanceOf[token][from] = balanceOf[token][from].sub(share);
total.elastic = total.elastic.sub(amount.to128());
total.base = total.base.sub(share.to128());
// There have to be at least 1000 shares left to prevent reseting the share/amount ratio (unless it's fully emptied)
require(
total.base >= MINIMUM_SHARE_BALANCE || total.base == 0,
"BentoBox: cannot empty"
);
totals[token] = total;
// Interactions
if (token_ == USE_ETHEREUM) {
// X2, X3: A revert or big gas usage in the WETH contract could block withdrawals, but WETH9 is fine.
IWETH(address(wethToken)).withdraw(amount);
// X2, X3: A revert or big gas usage could block, however, the to address is under control of the caller.
(bool success, ) = to.call{value: amount}("");
require(success, "BentoBox: ETH transfer failed");
} else {
// X2, X3: A malicious token could block withdrawal of just THAT token.
// masterContracts may want to take care not to rely on withdraw always succeeding.
token.safeTransfer(to, amount);
}
emit LogWithdraw(token, from, to, amount, share);
amountOut = amount;
shareOut = share;
}
/// @notice Transfer shares from a user account to another one.
/// @param token The ERC-20 token to transfer.
/// @param from which user to pull the tokens.
/// @param to which user to push the tokens.
/// @param share The amount of `token` in shares.
// Clones of master contracts can transfer from any account that has approved them
// F3 - Can it be combined with another similar function?
// F3: This isn't combined with transferMultiple for gas optimization
function transfer(
IERC20 token,
address from,
address to,
uint256 share
) public allowed(from) {
// Checks
require(to != address(0), "BentoBox: to not set"); // To avoid a bad UI from burning funds
// Effects
balanceOf[token][from] = balanceOf[token][from].sub(share);
balanceOf[token][to] = balanceOf[token][to].add(share);
emit LogTransfer(token, from, to, share);
}
/// @notice Transfer shares from a user account to multiple other ones.
/// @param token The ERC-20 token to transfer.
/// @param from which user to pull the tokens.
/// @param tos The receivers of the tokens.
/// @param shares The amount of `token` in shares for each receiver in `tos`.
// F3 - Can it be combined with another similar function?
// F3: This isn't combined with transfer for gas optimization
function transferMultiple(
IERC20 token,
address from,
address[] calldata tos,
uint256[] calldata shares
) public allowed(from) {
// Checks
require(tos[0] != address(0), "BentoBox: to[0] not set"); // To avoid a bad UI from burning funds
// Effects
uint256 totalAmount;
uint256 len = tos.length;
for (uint256 i = 0; i < len; i++) {
address to = tos[i];
balanceOf[token][to] = balanceOf[token][to].add(shares[i]);
totalAmount = totalAmount.add(shares[i]);
emit LogTransfer(token, from, to, shares[i]);
}
balanceOf[token][from] = balanceOf[token][from].sub(totalAmount);
}
/// @notice Flashloan ability.
/// @param borrower The address of the contract that implements and conforms to `IFlashBorrower` and handles the flashloan.
/// @param receiver Address of the token receiver.
/// @param token The address of the token to receive.
/// @param amount of the tokens to receive.
/// @param data The calldata to pass to the `borrower` contract.
// F5 - Checks-Effects-Interactions pattern followed? (SWC-107)
// F5: Not possible to follow this here, reentrancy has been reviewed
// F6 - Check for front-running possibilities, such as the approve function (SWC-114)
// F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount.
function flashLoan(
IFlashBorrower borrower,
address receiver,
IERC20 token,
uint256 amount,
bytes calldata data
) public {
uint256 fee = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION;
token.safeTransfer(receiver, amount);
borrower.onFlashLoan(msg.sender, token, amount, fee, data);
require(
_tokenBalanceOf(token) >= totals[token].addElastic(fee.to128()),
"BentoBox: Wrong amount"
);
emit LogFlashLoan(address(borrower), token, amount, fee, receiver);
}
/// @notice Support for batched flashloans. Useful to request multiple different `tokens` in a single transaction.
/// @param borrower The address of the contract that implements and conforms to `IBatchFlashBorrower` and handles the flashloan.
/// @param receivers An array of the token receivers. A one-to-one mapping with `tokens` and `amounts`.
/// @param tokens The addresses of the tokens.
/// @param amounts of the tokens for each receiver.
/// @param data The calldata to pass to the `borrower` contract.
// F5 - Checks-Effects-Interactions pattern followed? (SWC-107)
// F5: Not possible to follow this here, reentrancy has been reviewed
// F6 - Check for front-running possibilities, such as the approve function (SWC-114)
// F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount.
function batchFlashLoan(
IBatchFlashBorrower borrower,
address[] calldata receivers,
IERC20[] calldata tokens,
uint256[] calldata amounts,
bytes calldata data
) public {
uint256[] memory fees = new uint256[](tokens.length);
uint256 len = tokens.length;
for (uint256 i = 0; i < len; i++) {
uint256 amount = amounts[i];
fees[i] = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION;
tokens[i].safeTransfer(receivers[i], amounts[i]);
}
borrower.onBatchFlashLoan(msg.sender, tokens, amounts, fees, data);
for (uint256 i = 0; i < len; i++) {
IERC20 token = tokens[i];
require(
_tokenBalanceOf(token) >=
totals[token].addElastic(fees[i].to128()),
"BentoBox: Wrong amount"
);
emit LogFlashLoan(
address(borrower),
token,
amounts[i],
fees[i],
receivers[i]
);
}
}
/// @notice Sets the target percentage of the strategy for `token`.
/// @dev Only the owner of this contract is allowed to change this.
/// @param token The address of the token that maps to a strategy to change.
/// @param targetPercentage_ The new target in percent. Must be lesser or equal to `MAX_TARGET_PERCENTAGE`.
function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_)
public
onlyOwner
{
// Checks
require(
targetPercentage_ <= MAX_TARGET_PERCENTAGE,
"StrategyManager: Target too high"
);
// Effects
strategyData[token].targetPercentage = targetPercentage_;
emit LogStrategyTargetPercentage(token, targetPercentage_);
}
/// @notice Sets the contract address of a new strategy that conforms to `IStrategy` for `token`.
/// Must be called twice with the same arguments.
/// A new strategy becomes pending first and can be activated once `STRATEGY_DELAY` is over.
/// @dev Only the owner of this contract is allowed to change this.
/// @param token The address of the token that maps to a strategy to change.
/// @param newStrategy The address of the contract that conforms to `IStrategy`.
// F5 - Checks-Effects-Interactions pattern followed? (SWC-107)
// F5: Total amount is updated AFTER interaction. But strategy is under our control.
// C4 - Use block.timestamp only for long intervals (SWC-116)
// C4: block.timestamp is used for a period of 2 weeks, which is long enough
function setStrategy(IERC20 token, IStrategy newStrategy) public onlyOwner {
StrategyData memory data = strategyData[token];
IStrategy pending = pendingStrategy[token];
if (data.strategyStartDate == 0 || pending != newStrategy) {
pendingStrategy[token] = newStrategy;
// C1 - All math done through BoringMath (SWC-101)
// C1: Our sun will swallow the earth well before this overflows
data.strategyStartDate = (block.timestamp + STRATEGY_DELAY).to64();
emit LogStrategyQueued(token, newStrategy);
} else {
require(
data.strategyStartDate != 0 &&
block.timestamp >= data.strategyStartDate,
"StrategyManager: Too early"
);
if (address(strategy[token]) != address(0)) {
int256 balanceChange = strategy[token].exit(data.balance);
// Effects
if (balanceChange > 0) {
uint256 add = uint256(balanceChange);
totals[token].addElastic(add);
emit LogStrategyProfit(token, add);
} else if (balanceChange < 0) {
uint256 sub = uint256(-balanceChange);
totals[token].subElastic(sub);
emit LogStrategyLoss(token, sub);
}
emit LogStrategyDivest(token, data.balance);
}
strategy[token] = pending;
data.strategyStartDate = 0;
data.balance = 0;
pendingStrategy[token] = IStrategy(0);
emit LogStrategySet(token, newStrategy);
}
strategyData[token] = data;
}
/// @notice The actual process of yield farming. Executes the strategy of `token`.
/// Optionally does housekeeping if `balance` is true.
/// `maxChangeAmount` is relevant for skimming or withdrawing if `balance` is true.
/// @param token The address of the token for which a strategy is deployed.
/// @param balance True if housekeeping should be done.
/// @param maxChangeAmount The maximum amount for either pulling or pushing from/to the `IStrategy` contract.
// F5 - Checks-Effects-Interactions pattern followed? (SWC-107)
// F5: Total amount is updated AFTER interaction. But strategy is under our control.
// F5: Not followed to prevent reentrancy issues with flashloans and BentoBox skims?
function harvest(
IERC20 token,
bool balance,
uint256 maxChangeAmount
) public {
StrategyData memory data = strategyData[token];
IStrategy _strategy = strategy[token];
int256 balanceChange = _strategy.harvest(data.balance, msg.sender);
if (balanceChange == 0 && !balance) {
return;
}
uint256 totalElastic = totals[token].elastic;
if (balanceChange > 0) {
uint256 add = uint256(balanceChange);
totalElastic = totalElastic.add(add);
totals[token].elastic = totalElastic.to128();
emit LogStrategyProfit(token, add);
} else if (balanceChange < 0) {
// C1 - All math done through BoringMath (SWC-101)
// C1: balanceChange could overflow if it's max negative int128.
// But tokens with balances that large are not supported by the BentoBox.
uint256 sub = uint256(-balanceChange);
totalElastic = totalElastic.sub(sub);
totals[token].elastic = totalElastic.to128();
data.balance = data.balance.sub(sub.to128());
emit LogStrategyLoss(token, sub);
}
if (balance) {
uint256 targetBalance = totalElastic.mul(data.targetPercentage) /
100;
// if data.balance == targetBalance there is nothing to update
if (data.balance < targetBalance) {
uint256 amountOut = targetBalance.sub(data.balance);
if (maxChangeAmount != 0 && amountOut > maxChangeAmount) {
amountOut = maxChangeAmount;
}
token.safeTransfer(address(_strategy), amountOut);
data.balance = data.balance.add(amountOut.to128());
_strategy.skim(amountOut);
emit LogStrategyInvest(token, amountOut);
} else if (data.balance > targetBalance) {
uint256 amountIn = data.balance.sub(targetBalance.to128());
if (maxChangeAmount != 0 && amountIn > maxChangeAmount) {
amountIn = maxChangeAmount;
}
uint256 actualAmountIn = _strategy.withdraw(amountIn);
data.balance = data.balance.sub(actualAmountIn.to128());
emit LogStrategyDivest(token, actualAmountIn);
}
}
strategyData[token] = data;
}
// Contract should be able to receive ETH deposits to support deposit & skim
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
} | @notice Flashloan ability. @param borrower The address of the contract that implements and conforms to `IFlashBorrower` and handles the flashloan. @param receiver Address of the token receiver. @param token The address of the token to receive. @param amount of the tokens to receive. @param data The calldata to pass to the `borrower` contract. F5 - Checks-Effects-Interactions pattern followed? (SWC-107) F5: Not possible to follow this here, reentrancy has been reviewed F6 - Check for front-running possibilities, such as the approve function (SWC-114) F6: Slight grieving possible by withdrawing an amount before someone tries to flashloan close to the full amount. | function flashLoan(
IFlashBorrower borrower,
address receiver,
IERC20 token,
uint256 amount,
bytes calldata data
) public {
uint256 fee = amount.mul(FLASH_LOAN_FEE) / FLASH_LOAN_FEE_PRECISION;
token.safeTransfer(receiver, amount);
borrower.onFlashLoan(msg.sender, token, amount, fee, data);
require(
_tokenBalanceOf(token) >= totals[token].addElastic(fee.to128()),
"BentoBox: Wrong amount"
);
emit LogFlashLoan(address(borrower), token, amount, fee, receiver);
}
| 5,448,688 | [
1,
11353,
383,
304,
7123,
18,
225,
29759,
264,
1021,
1758,
434,
326,
6835,
716,
4792,
471,
356,
9741,
358,
1375,
45,
11353,
38,
15318,
264,
68,
471,
7372,
326,
9563,
383,
304,
18,
225,
5971,
5267,
434,
326,
1147,
5971,
18,
225,
1147,
1021,
1758,
434,
326,
1147,
358,
6798,
18,
225,
3844,
434,
326,
2430,
358,
6798,
18,
225,
501,
1021,
745,
892,
358,
1342,
358,
326,
1375,
70,
15318,
264,
68,
6835,
18,
478,
25,
300,
13074,
17,
29013,
17,
2465,
4905,
1936,
10860,
35,
261,
18746,
39,
17,
23054,
13,
478,
25,
30,
2288,
3323,
358,
2805,
333,
2674,
16,
283,
8230,
12514,
711,
2118,
10725,
329,
478,
26,
300,
2073,
364,
6641,
17,
8704,
28550,
16,
4123,
487,
326,
6617,
537,
445,
261,
18746,
39,
17,
22214,
13,
478,
26,
30,
348,
5099,
314,
566,
73,
6282,
3323,
635,
598,
9446,
310,
392,
3844,
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,
9563,
1504,
304,
12,
203,
3639,
467,
11353,
38,
15318,
264,
29759,
264,
16,
203,
3639,
1758,
5971,
16,
203,
3639,
467,
654,
39,
3462,
1147,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
1071,
288,
203,
3639,
2254,
5034,
14036,
273,
3844,
18,
16411,
12,
42,
16504,
67,
1502,
1258,
67,
8090,
41,
13,
342,
478,
16504,
67,
1502,
1258,
67,
8090,
41,
67,
3670,
26913,
31,
203,
3639,
1147,
18,
4626,
5912,
12,
24454,
16,
3844,
1769,
203,
203,
3639,
29759,
264,
18,
265,
11353,
1504,
304,
12,
3576,
18,
15330,
16,
1147,
16,
3844,
16,
14036,
16,
501,
1769,
203,
203,
3639,
2583,
12,
203,
5411,
389,
2316,
13937,
951,
12,
2316,
13,
1545,
19489,
63,
2316,
8009,
1289,
12462,
12,
21386,
18,
869,
10392,
1435,
3631,
203,
5411,
315,
38,
29565,
3514,
30,
24668,
3844,
6,
203,
3639,
11272,
203,
3639,
3626,
1827,
11353,
1504,
304,
12,
2867,
12,
70,
15318,
264,
3631,
1147,
16,
3844,
16,
14036,
16,
5971,
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
] |
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/test/TestProxy.sol | * @dev Space for implementation storage/* @dev Implementation contract/* @notice TestProxy constructor @param implementation Implementation contract @param data Initialization calldata/ | constructor(address implementation, bytes memory data) {
_impl = implementation;
Address.functionDelegateCall(implementation, data);
}
| 9,659,408 | [
1,
3819,
364,
4471,
2502,
19,
225,
25379,
6835,
19,
225,
7766,
3886,
3885,
225,
4471,
25379,
6835,
225,
501,
26586,
745,
892,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
4471,
16,
1731,
3778,
501,
13,
288,
203,
3639,
389,
11299,
273,
4471,
31,
203,
3639,
5267,
18,
915,
9586,
1477,
12,
30810,
16,
501,
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
] |
./full_match/42161/0x5bBacBb0EA1B5d450d92850cB8AB5f1AAD92C97A/sources/gist-17a8c2cf6c1a3e0ddc7d724e1e52f122/NFTEarthStaking.sol | * @notice Deposit NfteToken to the EARTHLINGS Pool @param _nfts Array of SingleNft structs @dev Commits 1 or more EARTHLINGS NFTs, each with an NfteToken amount to the EARTHLINGS pool.\ Each EARTHLINGS committed must attach an NfteToken amount >= 1 NfteToken and <= the EARTHLINGS pool cap amount./ | function depositEARTHLINGS(SingleNft[] calldata _nfts) external {
_depositNft(EARTHLINGS_POOL_ID, _nfts);
}
| 16,301,146 | [
1,
758,
1724,
423,
74,
736,
1345,
358,
326,
512,
985,
2455,
26789,
55,
8828,
225,
389,
82,
1222,
87,
1510,
434,
10326,
50,
1222,
8179,
225,
16854,
1282,
404,
578,
1898,
512,
985,
2455,
26789,
55,
423,
4464,
87,
16,
1517,
598,
392,
423,
74,
736,
1345,
3844,
358,
326,
512,
985,
2455,
26789,
55,
2845,
8403,
8315,
512,
985,
2455,
26789,
55,
16015,
1297,
3306,
392,
423,
74,
736,
1345,
3844,
1545,
404,
423,
74,
736,
1345,
471,
1648,
326,
512,
985,
2455,
26789,
55,
2845,
3523,
3844,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
443,
1724,
9250,
2455,
26789,
55,
12,
5281,
50,
1222,
8526,
745,
892,
389,
82,
1222,
87,
13,
3903,
288,
203,
3639,
389,
323,
1724,
50,
1222,
12,
9250,
2455,
26789,
55,
67,
20339,
67,
734,
16,
389,
82,
1222,
87,
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
] |
./full_match/1/0x6a2Df7Fd15612079D1a72001F3a921Db792B2738/sources/lib/solady/src/utils/DateTimeLib.sol | @dev Adds `numMonths` to the unix timestamp, and returns the result. Note: If the Gregorian calendar month of the result has less days than the Gregorian calendar month day of the `timestamp`, the result's month day will be the maximum possible value for the month. (e.g. from 29th Feb to 28th Feb) | function addMonths(uint256 timestamp, uint256 numMonths)
internal
pure
returns (uint256 result)
{
(uint256 year, uint256 month, uint256 day) = epochDayToDate(timestamp / 86400);
month = _sub(month + numMonths, 1);
result = _offsetted(year + month / 12, _add(month % 12, 1), day, timestamp);
}
| 17,179,011 | [
1,
3655,
1375,
2107,
19749,
68,
358,
326,
9753,
2858,
16,
471,
1135,
326,
563,
18,
3609,
30,
971,
326,
21913,
5686,
3138,
434,
326,
563,
711,
5242,
4681,
2353,
326,
21913,
5686,
3138,
2548,
434,
326,
1375,
5508,
9191,
326,
563,
1807,
3138,
2548,
903,
506,
326,
4207,
3323,
460,
364,
326,
3138,
18,
261,
73,
18,
75,
18,
628,
12899,
451,
5782,
70,
358,
9131,
451,
5782,
70,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
19749,
12,
11890,
5034,
2858,
16,
2254,
5034,
818,
19749,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
5034,
563,
13,
203,
565,
288,
203,
3639,
261,
11890,
5034,
3286,
16,
2254,
5034,
3138,
16,
2254,
5034,
2548,
13,
273,
7632,
4245,
31264,
12,
5508,
342,
21451,
1769,
203,
3639,
3138,
273,
389,
1717,
12,
7496,
397,
818,
19749,
16,
404,
1769,
203,
3639,
563,
273,
389,
3348,
2344,
12,
6874,
397,
3138,
342,
2593,
16,
389,
1289,
12,
7496,
738,
2593,
16,
404,
3631,
2548,
16,
2858,
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
] |
./partial_match/1/0x3Fdb3bd1ab409F0CBB2c4d919b2205ac881B99ED/sources/src/governor/Governor.sol | * @dev See {IGovernor-castVoteWithReasonAndParams}./ | function castVoteWithReasonAndParams(uint256 proposalId, uint8 support, string calldata reason, bytes memory params) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason, params);
}
| 9,366,591 | [
1,
9704,
288,
3047,
1643,
29561,
17,
4155,
19338,
1190,
8385,
1876,
1370,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4812,
19338,
1190,
8385,
1876,
1370,
12,
11890,
5034,
14708,
548,
16,
2254,
28,
2865,
16,
533,
745,
892,
3971,
16,
1731,
3778,
859,
13,
1071,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1758,
331,
20005,
273,
389,
3576,
12021,
5621,
203,
3639,
327,
389,
4155,
19338,
12,
685,
8016,
548,
16,
331,
20005,
16,
2865,
16,
3971,
16,
859,
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
] |
./full_match/80001/0x07c7D97B7c07192555FA813dE4da54285A182F84/sources/project_/contracts/interfaces/ISubscriptionManager.sol | Must only be called by a subscription contract
| function recordSubscriptionPayment(address _subscriber) external; | 840,246 | [
1,
10136,
1338,
506,
2566,
635,
279,
4915,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1409,
6663,
6032,
12,
2867,
389,
26410,
13,
3903,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* @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) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
/// Total amount of tokens
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _amount) public returns (bool success);
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 remaining);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function approve(address _spender, uint256 _amount) public returns (bool success);
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;
struct TokenVest
{
address vestAddress;
uint vestTokensLimit;
uint vestTill;
}
//balance in each address account
mapping(address => uint256) balances;
// list of tokens vest
TokenVest[] listofVest;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _amount The amount to be transferred.
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(isTransferAllowed(msg.sender,_amount));
require(_to != address(0));
require(balances[msg.sender] >= _amount && _amount > 0
&& balances[_to].add(_amount) > balances[_to]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
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];
}
function isTransferAllowed(address trans_from, uint amt) internal returns(bool)
{
for(uint i=0;i<listofVest.length;i++)
{
if(listofVest[i].vestAddress==trans_from)
{
if(now<=listofVest[i].vestTill)
{
if((balanceOf(trans_from).sub(amt)<listofVest[i].vestTokensLimit))
{
return false;
}
}
}
}
return true;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
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 _amount uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
require(isTransferAllowed(_from,_amount));
require(_to != address(0));
require(balances[_from] >= _amount);
require(allowed[_from][msg.sender] >= _amount);
require(_amount > 0 && balances[_to].add(_amount) > balances[_to]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
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 _amount The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
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 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken, Ownable {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public onlyOwner{
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
}
}
/**
* @title EthereumTravelToken Token
* @dev
*/
contract EthereumTravelToken is BurnableToken {
string public name ;
string public symbol ;
uint8 public decimals = 18 ;
address public AdvisorsAddress;
address public TeamAddress;
address public ReserveAddress;
TokenVest vestObject;
uint public TeamVestTimeLimit;
/**
*@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller
*/
function ()public payable {
revert();
}
/**
* @dev Constructor function to initialize the initial supply of token to the creator of the contract
*/
function EthereumTravelToken(
address wallet,
uint supply,
string nam,
string symb
) public {
owner = wallet;
totalSupply = supply;
totalSupply = totalSupply.mul( 10 ** uint256(decimals)); //Update total supply with the decimal amount
name = nam;
symbol = symb;
balances[wallet] = totalSupply;
TeamAddress=0xACE8841DF22F7b5d112db5f5AE913c7adA3457aF;
AdvisorsAddress=0x49695C3cB19aA4A32F6f465b54CE62e337A07c7b;
ReserveAddress=0xec599e12B45BB77B65291C30911d9B2c3991aB3D;
TeamVestTimeLimit = now + 365 days;
//Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
emit Transfer(address(0), msg.sender, totalSupply);
// transferring 18% of the tokens to team Address
transfer(TeamAddress, (totalSupply.mul(18)).div(100));
// transferring 1% of the tokens to advisors Address
transfer(AdvisorsAddress, (totalSupply.mul(1)).div(100));
// transferring 21% of the tokens to company Address
transfer(ReserveAddress, (totalSupply.mul(21)).div(100));
// vesting team address
vestTokens(TeamAddress,(totalSupply.mul(18)).div(100),TeamVestTimeLimit);
}
/**
*@dev helper method to get token details, name, symbol and totalSupply in one go
*/
function getTokenDetail() public view returns (string, string, uint256) {
return (name, symbol, totalSupply);
}
/**
*@dev internal method to add a vest in token memory
*/
function vestTokens(address ad, uint tkns, uint timelimit) internal {
vestObject = TokenVest({
vestAddress:ad,
vestTokensLimit:tkns,
vestTill:timelimit
});
listofVest.push(vestObject);
}
} | *@dev internal method to add a vest in token memory/ | function vestTokens(address ad, uint tkns, uint timelimit) internal {
vestObject = TokenVest({
vestAddress:ad,
vestTokensLimit:tkns,
vestTill:timelimit
});
listofVest.push(vestObject);
}
| 14,559,377 | [
1,
7236,
707,
358,
527,
279,
331,
395,
316,
1147,
3778,
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,
377,
445,
331,
395,
5157,
12,
2867,
1261,
16,
2254,
13030,
2387,
16,
2254,
1658,
19741,
13,
2713,
288,
203,
1377,
331,
395,
921,
273,
3155,
58,
395,
12590,
203,
1850,
331,
395,
1887,
30,
361,
16,
203,
1850,
331,
395,
5157,
3039,
30,
16099,
2387,
16,
203,
1850,
331,
395,
56,
737,
30,
8584,
19741,
203,
1377,
15549,
203,
1377,
666,
792,
58,
395,
18,
6206,
12,
26923,
921,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/GsnTypes.sol";
import "./interfaces/IPaymaster.sol";
import "./interfaces/IRelayHub.sol";
import "./utils/GsnEip712Library.sol";
import "./forwarder/IForwarder.sol";
/**
* Abstract base class to be inherited by a concrete Paymaster
* A subclass must implement:
* - preRelayedCall
* - postRelayedCall
*/
abstract contract BasePaymaster is IPaymaster, Ownable {
IRelayHub internal relayHub;
IForwarder public override trustedForwarder;
function getHubAddr() public override view returns (address) {
return address(relayHub);
}
//overhead of forwarder verify+signature, plus hub overhead.
uint256 constant public FORWARDER_HUB_OVERHEAD = 50000;
//These parameters are documented in IPaymaster.GasAndDataLimits
uint256 constant public PRE_RELAYED_CALL_GAS_LIMIT = 100000;
uint256 constant public POST_RELAYED_CALL_GAS_LIMIT = 110000;
uint256 constant public PAYMASTER_ACCEPTANCE_BUDGET = PRE_RELAYED_CALL_GAS_LIMIT + FORWARDER_HUB_OVERHEAD;
uint256 constant public CALLDATA_SIZE_LIMIT = 10500;
function getGasAndDataLimits()
public
override
virtual
view
returns (
IPaymaster.GasAndDataLimits memory limits
) {
return IPaymaster.GasAndDataLimits(
PAYMASTER_ACCEPTANCE_BUDGET,
PRE_RELAYED_CALL_GAS_LIMIT,
POST_RELAYED_CALL_GAS_LIMIT,
CALLDATA_SIZE_LIMIT
);
}
// this method must be called from preRelayedCall to validate that the forwarder
// is approved by the paymaster as well as by the recipient contract.
function _verifyForwarder(GsnTypes.RelayRequest calldata relayRequest)
public
view
{
require(address(trustedForwarder) == relayRequest.relayData.forwarder, "Forwarder is not trusted");
GsnEip712Library.verifyForwarderTrusted(relayRequest);
}
/*
* modifier to be used by recipients as access control protection for preRelayedCall & postRelayedCall
*/
modifier relayHubOnly() {
require(msg.sender == getHubAddr(), "can only be called by RelayHub");
_;
}
function setRelayHub(IRelayHub hub) public onlyOwner {
relayHub = hub;
}
function setTrustedForwarder(IForwarder forwarder) public onlyOwner {
trustedForwarder = forwarder;
}
/// check current deposit on relay hub.
function getRelayHubDeposit()
public
override
view
returns (uint) {
return relayHub.balanceOf(address(this));
}
// any money moved into the paymaster is transferred as a deposit.
// This way, we don't need to understand the RelayHub API in order to replenish
// the paymaster.
receive() external virtual payable {
require(address(relayHub) != address(0), "relay hub address not set");
relayHub.depositFor{value:msg.value}(address(this));
}
/// withdraw deposit from relayHub
function withdrawRelayHubDepositTo(uint amount, address payable target) public onlyOwner {
relayHub.withdraw(amount, target);
}
}
// SPDX-License-Identifier:MIT
// solhint-disable no-inline-assembly
pragma solidity >=0.7.6;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
return msg.data[0:msg.data.length-20];
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./forwarder/Forwarder.sol";
import "./BaseRelayRecipient.sol";
import "./utils/GsnUtils.sol";
/**
* batch forwarder support calling a method sendBatch in the forwarder itself.
* NOTE: the "target" of the request should be the BatchForwarder itself
*/
contract BatchForwarder is Forwarder, BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.batched.irelayrecipient";
constructor() {
//needed for sendBatch
trustedForwarder = address(this);
}
function sendBatch(address[] calldata targets, bytes[] calldata encodedFunctions) external {
require(targets.length == encodedFunctions.length, "BatchForwarder: wrong length");
address sender = _msgSender();
for (uint i = 0; i < targets.length; i++) {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory ret) = targets[i].call(abi.encodePacked(encodedFunctions[i], sender));
if (!success){
//re-throw the revert with the same revert reason.
GsnUtils.revertWithData(ret);
}
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./utils/RLPReader.sol";
import "./utils/GsnUtils.sol";
import "./interfaces/IRelayHub.sol";
import "./interfaces/IPenalizer.sol";
contract Penalizer is IPenalizer {
string public override versionPenalizer = "2.2.0+opengsn.penalizer.ipenalizer";
using ECDSA for bytes32;
uint256 public immutable override penalizeBlockDelay;
uint256 public immutable override penalizeBlockExpiration;
constructor(
uint256 _penalizeBlockDelay,
uint256 _penalizeBlockExpiration
) {
penalizeBlockDelay = _penalizeBlockDelay;
penalizeBlockExpiration = _penalizeBlockExpiration;
}
function isTransactionType1(bytes calldata rawTransaction) public pure returns (bool) {
return (uint8(rawTransaction[0]) == 1);
}
function isTransactionTypeValid(bytes calldata rawTransaction) public pure returns(bool) {
uint8 transactionTypeByte = uint8(rawTransaction[0]);
return (transactionTypeByte >= 0xc0 && transactionTypeByte <= 0xfe);
}
function decodeTransaction(bytes calldata rawTransaction) public pure returns (Transaction memory transaction) {
if (isTransactionType1(rawTransaction)) {
(transaction.nonce,
transaction.gasPrice,
transaction.gasLimit,
transaction.to,
transaction.value,
transaction.data) = RLPReader.decodeTransactionType1(rawTransaction);
} else {
(transaction.nonce,
transaction.gasPrice,
transaction.gasLimit,
transaction.to,
transaction.value,
transaction.data) = RLPReader.decodeLegacyTransaction(rawTransaction);
}
return transaction;
}
mapping(bytes32 => uint) public commits;
/**
* any sender can call "commit(keccak(encodedPenalizeFunction))", to make sure
* no-one can front-run it to claim this penalization
*/
function commit(bytes32 commitHash) external override {
uint256 readyBlockNumber = block.number + penalizeBlockDelay;
commits[commitHash] = readyBlockNumber;
emit CommitAdded(msg.sender, commitHash, readyBlockNumber);
}
modifier commitRevealOnly() {
bytes32 commitHash = keccak256(abi.encodePacked(keccak256(msg.data), msg.sender));
uint256 readyBlockNumber = commits[commitHash];
delete commits[commitHash];
// msg.sender can only be fake during off-chain view call, allowing Penalizer process to check transactions
if(msg.sender != address(0)) {
require(readyBlockNumber != 0, "no commit");
require(readyBlockNumber < block.number, "reveal penalize too soon");
require(readyBlockNumber + penalizeBlockExpiration > block.number, "reveal penalize too late");
}
_;
}
function penalizeRepeatedNonce(
bytes calldata unsignedTx1,
bytes calldata signature1,
bytes calldata unsignedTx2,
bytes calldata signature2,
IRelayHub hub,
uint256 randomValue
)
public
override
commitRevealOnly {
(randomValue);
_penalizeRepeatedNonce(unsignedTx1, signature1, unsignedTx2, signature2, hub);
}
function _penalizeRepeatedNonce(
bytes calldata unsignedTx1,
bytes calldata signature1,
bytes calldata unsignedTx2,
bytes calldata signature2,
IRelayHub hub
)
private
{
// If a relay attacked the system by signing multiple transactions with the same nonce
// (so only one is accepted), anyone can grab both transactions from the blockchain and submit them here.
// Check whether unsignedTx1 != unsignedTx2, that both are signed by the same address,
// and that unsignedTx1.nonce == unsignedTx2.nonce.
// If all conditions are met, relay is considered an "offending relay".
// The offending relay will be unregistered immediately, its stake will be forfeited and given
// to the address who reported it (msg.sender), thus incentivizing anyone to report offending relays.
// If reported via a relay, the forfeited stake is split between
// msg.sender (the relay used for reporting) and the address that reported it.
address addr1 = keccak256(unsignedTx1).recover(signature1);
address addr2 = keccak256(unsignedTx2).recover(signature2);
require(addr1 == addr2, "Different signer");
require(addr1 != address(0), "ecrecover failed");
Transaction memory decodedTx1 = decodeTransaction(unsignedTx1);
Transaction memory decodedTx2 = decodeTransaction(unsignedTx2);
// checking that the same nonce is used in both transaction, with both signed by the same address
// and the actual data is different
// note: we compare the hash of the tx to save gas over iterating both byte arrays
require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce");
bytes memory dataToCheck1 =
abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value);
bytes memory dataToCheck2 =
abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value);
require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal");
penalize(addr1, hub);
}
function penalizeIllegalTransaction(
bytes calldata unsignedTx,
bytes calldata signature,
IRelayHub hub,
uint256 randomValue
)
public
override
commitRevealOnly {
(randomValue);
_penalizeIllegalTransaction(unsignedTx, signature, hub);
}
function _penalizeIllegalTransaction(
bytes calldata unsignedTx,
bytes calldata signature,
IRelayHub hub
)
private
{
if (isTransactionTypeValid(unsignedTx)) {
Transaction memory decodedTx = decodeTransaction(unsignedTx);
if (decodedTx.to == address(hub)) {
bytes4 selector = GsnUtils.getMethodSig(decodedTx.data);
bool isWrongMethodCall = selector != IRelayHub.relayCall.selector;
bool isGasLimitWrong = GsnUtils.getParam(decodedTx.data, 4) != decodedTx.gasLimit;
require(
isWrongMethodCall || isGasLimitWrong,
"Legal relay transaction");
}
}
address relay = keccak256(unsignedTx).recover(signature);
require(relay != address(0), "ecrecover failed");
penalize(relay, hub);
}
function penalize(address relayWorker, IRelayHub hub) private {
hub.penalize(relayWorker, msg.sender);
}
}
/* solhint-disable avoid-low-level-calls */
/* solhint-disable no-inline-assembly */
/* solhint-disable not-rely-on-time */
/* solhint-disable avoid-tx-origin */
/* solhint-disable bracket-align */
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./utils/MinLibBytes.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/GsnUtils.sol";
import "./utils/GsnEip712Library.sol";
import "./utils/RelayHubValidator.sol";
import "./utils/GsnTypes.sol";
import "./interfaces/IRelayHub.sol";
import "./interfaces/IPaymaster.sol";
import "./forwarder/IForwarder.sol";
import "./interfaces/IStakeManager.sol";
contract RelayHub is IRelayHub, Ownable {
using SafeMath for uint256;
string public override versionHub = "2.2.0+opengsn.hub.irelayhub";
IStakeManager immutable override public stakeManager;
address immutable override public penalizer;
RelayHubConfig private config;
function getConfiguration() public override view returns (RelayHubConfig memory) {
return config;
}
function setConfiguration(RelayHubConfig memory _config) public override onlyOwner {
config = _config;
emit RelayHubConfigured(config);
}
uint256 public constant G_NONZERO = 16;
// maps relay worker's address to its manager's address
mapping(address => address) public override workerToManager;
// maps relay managers to the number of their workers
mapping(address => uint256) public override workerCount;
mapping(address => uint256) private balances;
uint256 public override deprecationBlock = type(uint).max;
constructor (
IStakeManager _stakeManager,
address _penalizer,
uint256 _maxWorkerCount,
uint256 _gasReserve,
uint256 _postOverhead,
uint256 _gasOverhead,
uint256 _maximumRecipientDeposit,
uint256 _minimumUnstakeDelay,
uint256 _minimumStake,
uint256 _dataGasCostPerByte,
uint256 _externalCallDataCostOverhead
) {
stakeManager = _stakeManager;
penalizer = _penalizer;
setConfiguration(RelayHubConfig(
_maxWorkerCount,
_gasReserve,
_postOverhead,
_gasOverhead,
_maximumRecipientDeposit,
_minimumUnstakeDelay,
_minimumStake,
_dataGasCostPerByte,
_externalCallDataCostOverhead
));
}
function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external override {
address relayManager = msg.sender;
require(
isRelayManagerStaked(relayManager),
"relay manager not staked"
);
require(workerCount[relayManager] > 0, "no relay workers");
emit RelayServerRegistered(relayManager, baseRelayFee, pctRelayFee, url);
}
function addRelayWorkers(address[] calldata newRelayWorkers) external override {
address relayManager = msg.sender;
uint256 newWorkerCount = workerCount[relayManager] + newRelayWorkers.length;
workerCount[relayManager] = newWorkerCount;
require(newWorkerCount <= config.maxWorkerCount, "too many workers");
require(
isRelayManagerStaked(relayManager),
"relay manager not staked"
);
for (uint256 i = 0; i < newRelayWorkers.length; i++) {
require(workerToManager[newRelayWorkers[i]] == address(0), "this worker has a manager");
workerToManager[newRelayWorkers[i]] = relayManager;
}
emit RelayWorkersAdded(relayManager, newRelayWorkers, newWorkerCount);
}
function depositFor(address target) public override payable {
uint256 amount = msg.value;
require(amount <= config.maximumRecipientDeposit, "deposit too big");
balances[target] = balances[target].add(amount);
emit Deposited(target, msg.sender, amount);
}
function balanceOf(address target) external override view returns (uint256) {
return balances[target];
}
function withdraw(uint256 amount, address payable dest) public override {
address payable account = msg.sender;
require(balances[account] >= amount, "insufficient funds");
balances[account] = balances[account].sub(amount);
dest.transfer(amount);
emit Withdrawn(account, dest, amount);
}
function calldataGasCost(uint256 length) public override view returns (uint256) {
return config.dataGasCostPerByte.mul(length);
}
function verifyGasAndDataLimits(
uint256 maxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
uint256 initialGasLeft,
uint256 externalGasLimit
)
private
view
returns (IPaymaster.GasAndDataLimits memory gasAndDataLimits, uint256 maxPossibleGas) {
gasAndDataLimits =
IPaymaster(relayRequest.relayData.paymaster).getGasAndDataLimits{gas:50000}();
require(msg.data.length <= gasAndDataLimits.calldataSizeLimit, "msg.data exceeded limit" );
uint256 dataGasCost = calldataGasCost(msg.data.length);
uint256 externalCallDataCost = externalGasLimit - initialGasLeft - config.externalCallDataCostOverhead;
uint256 txDataCostPerByte = externalCallDataCost/msg.data.length;
require(txDataCostPerByte <= G_NONZERO, "invalid externalGasLimit");
require(maxAcceptanceBudget >= gasAndDataLimits.acceptanceBudget, "acceptance budget too high");
require(gasAndDataLimits.acceptanceBudget >= gasAndDataLimits.preRelayedCallGasLimit, "acceptance budget too low");
maxPossibleGas =
config.gasOverhead.add(
gasAndDataLimits.preRelayedCallGasLimit).add(
gasAndDataLimits.postRelayedCallGasLimit).add(
relayRequest.request.gas).add(
dataGasCost).add(
externalCallDataCost);
// This transaction must have enough gas to forward the call to the recipient with the requested amount, and not
// run out of gas later in this function.
require(
externalGasLimit >= maxPossibleGas,
"no gas for innerRelayCall");
uint256 maxPossibleCharge = calculateCharge(
maxPossibleGas,
relayRequest.relayData
);
// We don't yet know how much gas will be used by the recipient, so we make sure there are enough funds to pay
// for the maximum possible charge.
require(maxPossibleCharge <= balances[relayRequest.relayData.paymaster],
"Paymaster balance too low");
}
struct RelayCallData {
bool success;
bytes4 functionSelector;
uint256 initialGasLeft;
bytes recipientContext;
bytes relayedCallReturnValue;
IPaymaster.GasAndDataLimits gasAndDataLimits;
RelayCallStatus status;
uint256 innerGasUsed;
uint256 maxPossibleGas;
uint256 gasBeforeInner;
bytes retData;
address relayManager;
uint256 dataGasCost;
}
function relayCall(
uint maxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint externalGasLimit
)
external
override
returns (bool paymasterAccepted, bytes memory returnValue)
{
RelayCallData memory vars;
vars.initialGasLeft = gasleft();
require(!isDeprecated(), "hub deprecated");
vars.functionSelector = relayRequest.request.data.length>=4 ? MinLibBytes.readBytes4(relayRequest.request.data, 0) : bytes4(0);
require(msg.sender == tx.origin, "relay worker must be EOA");
vars.relayManager = workerToManager[msg.sender];
require(vars.relayManager != address(0), "Unknown relay worker");
require(relayRequest.relayData.relayWorker == msg.sender, "Not a right worker");
require(
isRelayManagerStaked(vars.relayManager),
"relay manager not staked"
);
require(relayRequest.relayData.gasPrice <= tx.gasprice, "Invalid gas price");
require(externalGasLimit <= block.gaslimit, "Impossible gas limit");
(vars.gasAndDataLimits, vars.maxPossibleGas) =
verifyGasAndDataLimits(maxAcceptanceBudget, relayRequest, vars.initialGasLeft, externalGasLimit);
RelayHubValidator.verifyTransactionPacking(relayRequest,signature,approvalData);
{
//How much gas to pass down to innerRelayCall. must be lower than the default 63/64
// actually, min(gasleft*63/64, gasleft-GAS_RESERVE) might be enough.
uint256 innerGasLimit = gasleft()*63/64- config.gasReserve;
vars.gasBeforeInner = gasleft();
uint256 _tmpInitialGas = innerGasLimit + externalGasLimit + config.gasOverhead + config.postOverhead;
// Calls to the recipient are performed atomically inside an inner transaction which may revert in case of
// errors in the recipient. In either case (revert or regular execution) the return data encodes the
// RelayCallStatus value.
(bool success, bytes memory relayCallStatus) = address(this).call{gas:innerGasLimit}(
abi.encodeWithSelector(RelayHub.innerRelayCall.selector, relayRequest, signature, approvalData, vars.gasAndDataLimits,
_tmpInitialGas - gasleft(),
vars.maxPossibleGas
)
);
vars.success = success;
vars.innerGasUsed = vars.gasBeforeInner-gasleft();
(vars.status, vars.relayedCallReturnValue) = abi.decode(relayCallStatus, (RelayCallStatus, bytes));
if ( vars.relayedCallReturnValue.length>0 ) {
emit TransactionResult(vars.status, vars.relayedCallReturnValue);
}
}
{
vars.dataGasCost = calldataGasCost(msg.data.length);
if (!vars.success) {
//Failure cases where the PM doesn't pay
if (vars.status == RelayCallStatus.RejectedByPreRelayed ||
(vars.innerGasUsed <= vars.gasAndDataLimits.acceptanceBudget.add(vars.dataGasCost)) && (
vars.status == RelayCallStatus.RejectedByForwarder ||
vars.status == RelayCallStatus.RejectedByRecipientRevert //can only be thrown if rejectOnRecipientRevert==true
)) {
paymasterAccepted=false;
emit TransactionRejectedByPaymaster(
vars.relayManager,
relayRequest.relayData.paymaster,
relayRequest.request.from,
relayRequest.request.to,
msg.sender,
vars.functionSelector,
vars.innerGasUsed,
vars.relayedCallReturnValue);
return (false, vars.relayedCallReturnValue);
}
}
// We now perform the actual charge calculation, based on the measured gas used
uint256 gasUsed = (externalGasLimit - gasleft()) + config.gasOverhead;
uint256 charge = calculateCharge(gasUsed, relayRequest.relayData);
balances[relayRequest.relayData.paymaster] = balances[relayRequest.relayData.paymaster].sub(charge);
balances[vars.relayManager] = balances[vars.relayManager].add(charge);
emit TransactionRelayed(
vars.relayManager,
msg.sender,
relayRequest.request.from,
relayRequest.request.to,
relayRequest.relayData.paymaster,
vars.functionSelector,
vars.status,
charge);
return (true, "");
}
}
struct InnerRelayCallData {
uint256 balanceBefore;
bytes32 preReturnValue;
bool relayedCallSuccess;
bytes relayedCallReturnValue;
bytes recipientContext;
bytes data;
bool rejectOnRecipientRevert;
}
function innerRelayCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
IPaymaster.GasAndDataLimits calldata gasAndDataLimits,
uint256 totalInitialGas,
uint256 maxPossibleGas
)
external
returns (RelayCallStatus, bytes memory)
{
InnerRelayCallData memory vars;
// A new gas measurement is performed inside innerRelayCall, since
// due to EIP150 available gas amounts cannot be directly compared across external calls
// This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the
// recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction.
require(msg.sender == address(this), "Must be called by RelayHub");
// If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on
// the recipient. The recipient will still be charged for the used gas by the relay.
// The paymaster is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and
// post state to ensure this doesn't happen.
vars.balanceBefore = balances[relayRequest.relayData.paymaster];
// First preRelayedCall is executed.
// Note: we open a new block to avoid growing the stack too much.
vars.data = abi.encodeWithSelector(
IPaymaster.preRelayedCall.selector,
relayRequest, signature, approvalData, maxPossibleGas
);
{
bool success;
bytes memory retData;
(success, retData) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.preRelayedCallGasLimit}(vars.data);
if (!success) {
GsnEip712Library.truncateInPlace(retData);
revertWithStatus(RelayCallStatus.RejectedByPreRelayed, retData);
}
(vars.recipientContext, vars.rejectOnRecipientRevert) = abi.decode(retData, (bytes,bool));
}
// The actual relayed call is now executed. The sender's address is appended at the end of the transaction data
{
bool forwarderSuccess;
(forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature);
if ( !forwarderSuccess ) {
revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue);
}
if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) {
// we trusted the recipient, but it reverted...
revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue);
}
}
// Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate
// We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate
// accounting.
vars.data = abi.encodeWithSelector(
IPaymaster.postRelayedCall.selector,
vars.recipientContext,
vars.relayedCallSuccess,
totalInitialGas - gasleft(), /*gasUseWithoutPost*/
relayRequest.relayData
);
{
(bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasAndDataLimits.postRelayedCallGasLimit}(vars.data);
if (!successPost) {
revertWithStatus(RelayCallStatus.PostRelayedFailed, ret);
}
}
if (balances[relayRequest.relayData.paymaster] < vars.balanceBefore) {
revertWithStatus(RelayCallStatus.PaymasterBalanceChanged, "");
}
return (vars.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed, vars.relayedCallReturnValue);
}
/**
* @dev Reverts the transaction with return data set to the ABI encoding of the status argument (and revert reason data)
*/
function revertWithStatus(RelayCallStatus status, bytes memory ret) private pure {
bytes memory data = abi.encode(status, ret);
GsnEip712Library.truncateInPlace(data);
assembly {
let dataSize := mload(data)
let dataPtr := add(data, 32)
revert(dataPtr, dataSize)
}
}
function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) public override virtual view returns (uint256) {
return relayData.baseRelayFee.add((gasUsed.mul(relayData.gasPrice).mul(relayData.pctRelayFee.add(100))).div(100));
}
function isRelayManagerStaked(address relayManager) public override view returns (bool) {
return stakeManager.isRelayManagerStaked(relayManager, address(this), config.minimumStake, config.minimumUnstakeDelay);
}
function deprecateHub(uint256 fromBlock) public override onlyOwner {
require(deprecationBlock > block.number, "Already deprecated");
deprecationBlock = fromBlock;
emit HubDeprecated(fromBlock);
}
function isDeprecated() public override view returns (bool) {
return block.number >= deprecationBlock;
}
modifier penalizerOnly () {
require(msg.sender == penalizer, "Not penalizer");
_;
}
function penalize(address relayWorker, address payable beneficiary) external override penalizerOnly {
address relayManager = workerToManager[relayWorker];
// The worker must be controlled by a manager with a locked stake
require(relayManager != address(0), "Unknown relay worker");
require(
isRelayManagerStaked(relayManager),
"relay manager not staked"
);
IStakeManager.StakeInfo memory stakeInfo = stakeManager.getStakeInfo(relayManager);
stakeManager.penalizeRelayManager(relayManager, beneficiary, stakeInfo.stake);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IStakeManager.sol";
contract StakeManager is IStakeManager {
using SafeMath for uint256;
string public override versionSM = "2.2.0+opengsn.stakemanager.istakemanager";
uint256 public immutable override maxUnstakeDelay;
/// maps relay managers to their stakes
mapping(address => StakeInfo) public stakes;
function getStakeInfo(address relayManager) external override view returns (StakeInfo memory stakeInfo) {
return stakes[relayManager];
}
/// maps relay managers to a map of addressed of their authorized hubs to the information on that hub
mapping(address => mapping(address => RelayHubInfo)) public authorizedHubs;
constructor(uint256 _maxUnstakeDelay) {
maxUnstakeDelay = _maxUnstakeDelay;
}
function setRelayManagerOwner(address payable owner) external override {
require(owner != address(0), "invalid owner");
require(stakes[msg.sender].owner == address(0), "already owned");
stakes[msg.sender].owner = owner;
emit OwnerSet(msg.sender, owner);
}
/// Put a stake for a relayManager and set its unstake delay. Only the owner can call this function.
/// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
function stakeForRelayManager(address relayManager, uint256 unstakeDelay) external override payable ownerOnly(relayManager) {
require(unstakeDelay >= stakes[relayManager].unstakeDelay, "unstakeDelay cannot be decreased");
require(unstakeDelay <= maxUnstakeDelay, "unstakeDelay too big");
stakes[relayManager].stake += msg.value;
stakes[relayManager].unstakeDelay = unstakeDelay;
emit StakeAdded(relayManager, stakes[relayManager].owner, stakes[relayManager].stake, stakes[relayManager].unstakeDelay);
}
function unlockStake(address relayManager) external override ownerOnly(relayManager) {
StakeInfo storage info = stakes[relayManager];
require(info.withdrawBlock == 0, "already pending");
uint withdrawBlock = block.number.add(info.unstakeDelay);
info.withdrawBlock = withdrawBlock;
emit StakeUnlocked(relayManager, msg.sender, withdrawBlock);
}
function withdrawStake(address relayManager) external override ownerOnly(relayManager) {
StakeInfo storage info = stakes[relayManager];
require(info.withdrawBlock > 0, "Withdrawal is not scheduled");
require(info.withdrawBlock <= block.number, "Withdrawal is not due");
uint256 amount = info.stake;
info.stake = 0;
info.withdrawBlock = 0;
msg.sender.transfer(amount);
emit StakeWithdrawn(relayManager, msg.sender, amount);
}
modifier ownerOnly (address relayManager) {
StakeInfo storage info = stakes[relayManager];
require(info.owner == msg.sender, "not owner");
_;
}
modifier managerOnly () {
StakeInfo storage info = stakes[msg.sender];
require(info.owner != address(0), "not manager");
_;
}
function authorizeHubByOwner(address relayManager, address relayHub) external ownerOnly(relayManager) override {
_authorizeHub(relayManager, relayHub);
}
function authorizeHubByManager(address relayHub) external managerOnly override {
_authorizeHub(msg.sender, relayHub);
}
function _authorizeHub(address relayManager, address relayHub) internal {
authorizedHubs[relayManager][relayHub].removalBlock = uint(-1);
emit HubAuthorized(relayManager, relayHub);
}
function unauthorizeHubByOwner(address relayManager, address relayHub) external override ownerOnly(relayManager) {
_unauthorizeHub(relayManager, relayHub);
}
function unauthorizeHubByManager(address relayHub) external override managerOnly {
_unauthorizeHub(msg.sender, relayHub);
}
function _unauthorizeHub(address relayManager, address relayHub) internal {
RelayHubInfo storage hubInfo = authorizedHubs[relayManager][relayHub];
require(hubInfo.removalBlock == uint(-1), "hub not authorized");
uint256 removalBlock = block.number.add(stakes[relayManager].unstakeDelay);
hubInfo.removalBlock = removalBlock;
emit HubUnauthorized(relayManager, relayHub, removalBlock);
}
function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay)
external
override
view
returns (bool) {
StakeInfo storage info = stakes[relayManager];
bool isAmountSufficient = info.stake >= minAmount;
bool isDelaySufficient = info.unstakeDelay >= minUnstakeDelay;
bool isStakeLocked = info.withdrawBlock == 0;
bool isHubAuthorized = authorizedHubs[relayManager][relayHub].removalBlock == uint(-1);
return
isAmountSufficient &&
isDelaySufficient &&
isStakeLocked &&
isHubAuthorized;
}
/// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way.
/// @param relayManager - entry to penalize
/// @param beneficiary - address that receives half of the penalty amount
/// @param amount - amount to withdraw from stake
function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external override {
uint256 removalBlock = authorizedHubs[relayManager][msg.sender].removalBlock;
require(removalBlock != 0, "hub not authorized");
require(removalBlock > block.number, "hub authorization expired");
// Half of the stake will be burned (sent to address 0)
require(stakes[relayManager].stake >= amount, "penalty exceeds stake");
stakes[relayManager].stake = SafeMath.sub(stakes[relayManager].stake, amount);
uint256 toBurn = SafeMath.div(amount, 2);
uint256 reward = SafeMath.sub(amount, toBurn);
// Ether is burned and transferred
address(0).transfer(toBurn);
beneficiary.transfer(reward);
emit StakePenalized(relayManager, beneficiary, reward);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./IForwarder.sol";
contract Forwarder is IForwarder {
using ECDSA for bytes32;
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil";
string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)";
mapping(bytes32 => bool) public typeHashes;
mapping(bytes32 => bool) public domains;
// Nonces of senders, used to prevent replay attacks
mapping(address => uint256) private nonces;
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function getNonce(address from)
public view override
returns (uint256) {
return nonces[from];
}
constructor() {
string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")"));
registerRequestTypeInternal(requestType);
}
function verify(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig)
external override view {
_verifyNonce(req);
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
}
function execute(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig
)
external payable
override
returns (bool success, bytes memory ret) {
_verifySig(req, domainSeparator, requestTypeHash, suffixData, sig);
_verifyAndUpdateNonce(req);
require(req.validUntil == 0 || req.validUntil > block.number, "FWD: request expired");
uint gasForTransfer = 0;
if ( req.value != 0 ) {
gasForTransfer = 40000; //buffer in case we need to move eth after the transaction.
}
bytes memory callData = abi.encodePacked(req.data, req.from);
require(gasleft()*63/64 >= req.gas + gasForTransfer, "FWD: insufficient gas");
// solhint-disable-next-line avoid-low-level-calls
(success,ret) = req.to.call{gas : req.gas, value : req.value}(callData);
if ( req.value != 0 && address(this).balance>0 ) {
// can't fail: req.from signed (off-chain) the request, so it must be an EOA...
payable(req.from).transfer(address(this).balance);
}
return (success,ret);
}
function _verifyNonce(ForwardRequest calldata req) internal view {
require(nonces[req.from] == req.nonce, "FWD: nonce mismatch");
}
function _verifyAndUpdateNonce(ForwardRequest calldata req) internal {
require(nonces[req.from]++ == req.nonce, "FWD: nonce mismatch");
}
function registerRequestType(string calldata typeName, string calldata typeSuffix) external override {
for (uint i = 0; i < bytes(typeName).length; i++) {
bytes1 c = bytes(typeName)[i];
require(c != "(" && c != ")", "FWD: invalid typename");
}
string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix));
registerRequestTypeInternal(requestType);
}
function registerDomainSeparator(string calldata name, string calldata version) external override {
uint256 chainId;
/* solhint-disable-next-line no-inline-assembly */
assembly { chainId := chainid() }
bytes memory domainValue = abi.encode(
keccak256(bytes(EIP712_DOMAIN_TYPE)),
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this));
bytes32 domainHash = keccak256(domainValue);
domains[domainHash] = true;
emit DomainRegistered(domainHash, domainValue);
}
function registerRequestTypeInternal(string memory requestType) internal {
bytes32 requestTypehash = keccak256(bytes(requestType));
typeHashes[requestTypehash] = true;
emit RequestTypeRegistered(requestTypehash, requestType);
}
function _verifySig(
ForwardRequest calldata req,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata sig)
internal
view
{
require(domains[domainSeparator], "FWD: unregistered domain sep.");
require(typeHashes[requestTypeHash], "FWD: unregistered typehash");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01", domainSeparator,
keccak256(_getEncoded(req, requestTypeHash, suffixData))
));
require(digest.recover(sig) == req.from, "FWD: signature mismatch");
}
function _getEncoded(
ForwardRequest calldata req,
bytes32 requestTypeHash,
bytes calldata suffixData
)
public
pure
returns (
bytes memory
) {
// we use encodePacked since we append suffixData as-is, not as dynamic param.
// still, we must make sure all first params are encoded as abi.encode()
// would encode them - as 256-bit-wide params.
return abi.encodePacked(
requestTypeHash,
uint256(uint160(req.from)),
uint256(uint160(req.to)),
req.value,
req.gas,
req.nonce,
keccak256(req.data),
req.validUntil,
suffixData
);
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
interface IForwarder {
struct ForwardRequest {
address from;
address to;
uint256 value;
uint256 gas;
uint256 nonce;
bytes data;
uint256 validUntil;
}
event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue);
event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr);
function getNonce(address from)
external view
returns(uint256);
/**
* verify the transaction would execute.
* validate the signature and the nonce of the request.
* revert if either signature or nonce are incorrect.
* also revert if domainSeparator or requestTypeHash are not registered.
*/
function verify(
ForwardRequest calldata forwardRequest,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata signature
) external view;
/**
* execute a transaction
* @param forwardRequest - all transaction parameters
* @param domainSeparator - domain used when signing this request
* @param requestTypeHash - request type used when signing this request.
* @param suffixData - the extension data used when signing this request.
* @param signature - signature to validate.
*
* the transaction is verified, and then executed.
* the success and ret of "call" are returned.
* This method would revert only verification errors. target errors
* are reported using the returned "success" and ret string
*/
function execute(
ForwardRequest calldata forwardRequest,
bytes32 domainSeparator,
bytes32 requestTypeHash,
bytes calldata suffixData,
bytes calldata signature
)
external payable
returns (bool success, bytes memory ret);
/**
* Register a new Request typehash.
* @param typeName - the name of the request type.
* @param typeSuffix - any extra data after the generic params.
* (must add at least one param. The generic ForwardRequest type is always registered by the constructor)
*/
function registerRequestType(string calldata typeName, string calldata typeSuffix) external;
/**
* Register a new domain separator.
* The domain separator must have the following fields: name,version,chainId, verifyingContract.
* the chainId is the current network's chainId, and the verifyingContract is this forwarder.
* This method is given the domain name and version to create and register the domain separator value.
* @param name the domain's display name
* @param version the domain/protocol version
*/
function registerDomainSeparator(string calldata name, string calldata version) external;
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../Forwarder.sol";
// helper class for testing the forwarder.
contract TestForwarder {
function callExecute(Forwarder forwarder, Forwarder.ForwardRequest memory req,
bytes32 domainSeparator, bytes32 requestTypeHash, bytes memory suffixData, bytes memory sig) public payable {
(bool success, bytes memory error) = forwarder.execute{value:msg.value}(req, domainSeparator, requestTypeHash, suffixData, sig);
emit Result(success, success ? "" : this.decodeErrorMessage(error));
}
event Result(bool success, string error);
function decodeErrorMessage(bytes calldata ret) external pure returns (string memory message) {
//decode evert string: assume it has a standard Error(string) signature: simply skip the (selector,offset,length) fields
if ( ret.length>4+32+32 ) {
return abi.decode(ret[4:], (string));
}
//unknown buffer. return as-is
return string(ret);
}
function getChainId() public pure returns (uint256 id){
/* solhint-disable-next-line no-inline-assembly */
assembly { id := chainid() }
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
import "../../BaseRelayRecipient.sol";
contract TestForwarderTarget is BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.test.recipient";
constructor(address forwarder) {
trustedForwarder = forwarder;
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
event TestForwarderMessage(string message, bytes realMsgData, address realSender, address msgSender, address origin);
function emitMessage(string memory message) public {
// solhint-disable-next-line avoid-tx-origin
emit TestForwarderMessage(message, _msgData(), _msgSender(), msg.sender, tx.origin);
}
function publicMsgSender() public view returns (address) {
return _msgSender();
}
function publicMsgData() public view returns (bytes memory) {
return _msgData();
}
function mustReceiveEth(uint value) public payable {
require( msg.value == value, "didn't receive value");
}
event Reverting(string message);
function testRevert() public {
require(address(this) == address(0), "always fail");
emit Reverting("if you see this revert failed...");
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
interface IPaymaster {
/**
* @param acceptanceBudget -
* Paymaster expected gas budget to accept (or reject) a request
* This a gas required by any calculations that might need to reject the
* transaction, by preRelayedCall, forwarder and recipient.
* See value in BasePaymaster.PAYMASTER_ACCEPTANCE_BUDGET
* Transaction that gets rejected above that gas usage is on the paymaster's expense.
* As long this value is above preRelayedCallGasLimit (see defaults in BasePaymaster), the
* Paymaster is guaranteed it will never pay for rejected transactions.
* If this value is below preRelayedCallGasLimt, it might might make Paymaster open to a "griefing" attack.
*
* Specifying value too high might make the call rejected by some relayers.
*
* From a Relay's point of view, this is the highest gas value a paymaster might "grief" the relay,
* since the paymaster will pay anything above that (regardless if the tx reverts)
*
* @param preRelayedCallGasLimit - the max gas usage of preRelayedCall. any revert (including OOG)
* of preRelayedCall is a reject by the paymaster.
* as long as acceptanceBudget is above preRelayedCallGasLimit, any such revert (including OOG)
* is not payed by the paymaster.
* @param postRelayedCallGasLimit - the max gas usage of postRelayedCall.
* note that an OOG will revert the transaction, but the paymaster already committed to pay,
* so the relay will get compensated, at the expense of the paymaster
*/
struct GasAndDataLimits {
uint256 acceptanceBudget;
uint256 preRelayedCallGasLimit;
uint256 postRelayedCallGasLimit;
uint256 calldataSizeLimit;
}
/**
* Return the Gas Limits and msg.data max size constants used by the Paymaster.
*/
function getGasAndDataLimits()
external
view
returns (
GasAndDataLimits memory limits
);
function trustedForwarder() external view returns (IForwarder);
/**
* return the relayHub of this contract.
*/
function getHubAddr() external view returns (address);
/**
* Can be used to determine if the contract can pay for incoming calls before making any.
* @return the paymaster's deposit in the RelayHub.
*/
function getRelayHubDeposit() external view returns (uint256);
/**
* Called by Relay (and RelayHub), to validate if the paymaster agrees to pay for this call.
*
* MUST be protected with relayHubOnly() in case it modifies state.
*
* The Paymaster rejects by the following "revert" operations
* - preRelayedCall() method reverts
* - the forwarder reverts because of nonce or signature error
* - the paymaster returned "rejectOnRecipientRevert", and the recipient contract reverted.
* In any of the above cases, all paymaster calls (and recipient call) are reverted.
* In any other case, the paymaster agrees to pay for the gas cost of the transaction (note
* that this includes also postRelayedCall revert)
*
* The rejectOnRecipientRevert flag means the Paymaster "delegate" the rejection to the recipient
* code. It also means the Paymaster trust the recipient to reject fast: both preRelayedCall,
* forwarder check and receipient checks must fit into the GasLimits.acceptanceBudget,
* otherwise the TX is paid by the Paymaster.
*
* @param relayRequest - the full relay request structure
* @param signature - user's EIP712-compatible signature of the {@link relayRequest}.
* Note that in most cases the paymaster shouldn't try use it at all. It is always checked
* by the forwarder immediately after preRelayedCall returns.
* @param approvalData - extra dapp-specific data (e.g. signature from trusted party)
* @param maxPossibleGas - based on values returned from {@link getGasAndDataLimits},
* the RelayHub will calculate the maximum possible amount of gas the user may be charged for.
* In order to convert this value to wei, the Paymaster has to call "relayHub.calculateCharge()"
* return:
* a context to be passed to postRelayedCall
* rejectOnRecipientRevert - TRUE if paymaster want to reject the TX if the recipient reverts.
* FALSE means that rejects by the recipient will be completed on chain, and paid by the paymaster.
* (note that in the latter case, the preRelayedCall and postRelayedCall are not reverted).
*/
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
returns (bytes memory context, bool rejectOnRecipientRevert);
/**
* This method is called after the actual relayed function call.
* It may be used to record the transaction (e.g. charge the caller by some contract logic) for this call.
*
* MUST be protected with relayHubOnly() in case it modifies state.
*
* @param context - the call context, as returned by the preRelayedCall
* @param success - true if the relayed call succeeded, false if it reverted
* @param gasUseWithoutPost - the actual amount of gas used by the entire transaction, EXCEPT
* the gas used by the postRelayedCall itself.
* @param relayData - the relay params of the request. can be used by relayHub.calculateCharge()
*
* Revert in this functions causes a revert of the client's relayed call (and preRelayedCall(), but the Paymaster
* is still committed to pay the relay for the entire transaction.
*/
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
) external;
function versionPaymaster() external view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
import "./IRelayHub.sol";
interface IPenalizer {
event CommitAdded(address indexed sender, bytes32 indexed commitHash, uint256 readyBlockNumber);
struct Transaction {
uint256 nonce;
uint256 gasPrice;
uint256 gasLimit;
address to;
uint256 value;
bytes data;
}
function commit(bytes32 commitHash) external;
function penalizeRepeatedNonce(
bytes calldata unsignedTx1,
bytes calldata signature1,
bytes calldata unsignedTx2,
bytes calldata signature2,
IRelayHub hub,
uint256 randomValue
) external;
function penalizeIllegalTransaction(
bytes calldata unsignedTx,
bytes calldata signature,
IRelayHub hub,
uint256 randomValue
) external;
function versionPenalizer() external view returns (string memory);
function penalizeBlockDelay() external view returns (uint256);
function penalizeBlockExpiration() external view returns (uint256);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
import "./IStakeManager.sol";
interface IRelayHub {
struct RelayHubConfig {
// maximum number of worker accounts allowed per manager
uint256 maxWorkerCount;
// Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions
uint256 gasReserve;
// Gas overhead to calculate gasUseWithoutPost
uint256 postOverhead;
// Gas cost of all relayCall() instructions after actual 'calculateCharge()'
// Assume that relay has non-zero balance (costs 15'000 more otherwise).
uint256 gasOverhead;
// Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits.
uint256 maximumRecipientDeposit;
// Minimum unstake delay blocks of a relay manager's stake on the StakeManager
uint256 minimumUnstakeDelay;
// Minimum stake a relay can have. An attack on the network will never cost less than half this value.
uint256 minimumStake;
// relayCall()'s msg.data upper bound gas cost per byte
uint256 dataGasCostPerByte;
// relayCalls() minimal gas overhead when calculating cost of putting tx on chain.
uint256 externalCallDataCostOverhead;
}
event RelayHubConfigured(RelayHubConfig config);
/// Emitted when a relay server registers or updates its details
/// Looking at these events lets a client discover relay servers
event RelayServerRegistered(
address indexed relayManager,
uint256 baseRelayFee,
uint256 pctRelayFee,
string relayUrl
);
/// Emitted when relays are added by a relayManager
event RelayWorkersAdded(
address indexed relayManager,
address[] newRelayWorkers,
uint256 workersCount
);
/// Emitted when an account withdraws funds from RelayHub.
event Withdrawn(
address indexed account,
address indexed dest,
uint256 amount
);
/// Emitted when depositFor is called, including the amount and account that was funded.
event Deposited(
address indexed paymaster,
address indexed from,
uint256 amount
);
/// Emitted when an attempt to relay a call fails and Paymaster does not accept the transaction.
/// The actual relayed call was not executed, and the recipient not charged.
/// @param reason contains a revert reason returned from preRelayedCall or forwarder.
event TransactionRejectedByPaymaster(
address indexed relayManager,
address indexed paymaster,
address indexed from,
address to,
address relayWorker,
bytes4 selector,
uint256 innerGasUsed,
bytes reason
);
/// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be
/// indicated in the status field.
/// Useful when monitoring a relay's operation and relayed calls to a contract.
/// Charge is the ether value deducted from the recipient's balance, paid to the relay's manager.
event TransactionRelayed(
address indexed relayManager,
address indexed relayWorker,
address indexed from,
address to,
address paymaster,
bytes4 selector,
RelayCallStatus status,
uint256 charge
);
event TransactionResult(
RelayCallStatus status,
bytes returnValue
);
event HubDeprecated(uint256 fromBlock);
/// Reason error codes for the TransactionRelayed event
/// @param OK - the transaction was successfully relayed and execution successful - never included in the event
/// @param RelayedCallFailed - the transaction was relayed, but the relayed call failed
/// @param RejectedByPreRelayed - the transaction was not relayed due to preRelatedCall reverting
/// @param RejectedByForwarder - the transaction was not relayed due to forwarder check (signature,nonce)
/// @param PostRelayedFailed - the transaction was relayed and reverted due to postRelatedCall reverting
/// @param PaymasterBalanceChanged - the transaction was relayed and reverted due to the paymaster balance change
enum RelayCallStatus {
OK,
RelayedCallFailed,
RejectedByPreRelayed,
RejectedByForwarder,
RejectedByRecipientRevert,
PostRelayedFailed,
PaymasterBalanceChanged
}
/// Add new worker addresses controlled by sender who must be a staked Relay Manager address.
/// Emits a RelayWorkersAdded event.
/// This function can be called multiple times, emitting new events
function addRelayWorkers(address[] calldata newRelayWorkers) external;
function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external;
// Balance management
/// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only
/// be withdrawn by the contract itself, by calling withdraw.
/// Emits a Deposited event.
function depositFor(address target) external payable;
/// Withdraws from an account's balance, sending it back to it. Relay managers call this to retrieve their revenue, and
/// contracts can also use it to reduce their funding.
/// Emits a Withdrawn event.
function withdraw(uint256 amount, address payable dest) external;
// Relaying
/// Relays a transaction. For this to succeed, multiple conditions must be met:
/// - Paymaster's "preRelayCall" method must succeed and not revert
/// - the sender must be a registered Relay Worker that the user signed
/// - the transaction's gas price must be equal or larger than the one that was signed by the sender
/// - the transaction must have enough gas to run all internal transactions if they use all gas available to them
/// - the Paymaster must have enough balance to pay the Relay Worker for the scenario when all gas is spent
///
/// If all conditions are met, the call will be relayed and the recipient charged.
///
/// Arguments:
/// @param maxAcceptanceBudget - max valid value for paymaster.getGasLimits().acceptanceBudget
/// @param relayRequest - all details of the requested relayed call
/// @param signature - client's EIP-712 signature over the relayRequest struct
/// @param approvalData: dapp-specific data forwarded to preRelayedCall.
/// This value is *not* verified by the Hub. For example, it can be used to pass a signature to the Paymaster
/// @param externalGasLimit - the value passed as gasLimit to the transaction.
///
/// Emits a TransactionRelayed event.
function relayCall(
uint maxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint externalGasLimit
)
external
returns (bool paymasterAccepted, bytes memory returnValue);
function penalize(address relayWorker, address payable beneficiary) external;
function setConfiguration(RelayHubConfig memory _config) external;
// Deprecate hub (reverting relayCall()) from block number 'fromBlock'
// Can only be called by owner
function deprecateHub(uint256 fromBlock) external;
/// The fee is expressed as a base fee in wei plus percentage on actual charge.
/// E.g. a value of 40 stands for a 40% fee, so the recipient will be
/// charged for 1.4 times the spent amount.
function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) external view returns (uint256);
/* getters */
/// Returns the whole hub configuration
function getConfiguration() external view returns (RelayHubConfig memory config);
function calldataGasCost(uint256 length) external view returns (uint256);
function workerToManager(address worker) external view returns(address);
function workerCount(address manager) external view returns(uint256);
/// Returns an account's deposits. It can be either a deposit of a paymaster, or a revenue of a relay manager.
function balanceOf(address target) external view returns (uint256);
function stakeManager() external view returns (IStakeManager);
function penalizer() external view returns (address);
/// Uses StakeManager info to decide if the Relay Manager can be considered staked
/// @return true if stake size and delay satisfy all requirements
function isRelayManagerStaked(address relayManager) external view returns(bool);
// Checks hubs' deprecation status
function isDeprecated() external view returns (bool);
// Returns the block number from which the hub no longer allows relaying calls.
function deprecationBlock() external view returns (uint256);
/// @return a SemVer-compliant version of the hub contract
function versionHub() external view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise (if the call was made directly and not through the forwarder), return `msg.data`
* should be used in the contract instead of msg.data, where this difference matters.
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface IStakeManager {
/// Emitted when a stake or unstakeDelay are initialized or increased
event StakeAdded(
address indexed relayManager,
address indexed owner,
uint256 stake,
uint256 unstakeDelay
);
/// Emitted once a stake is scheduled for withdrawal
event StakeUnlocked(
address indexed relayManager,
address indexed owner,
uint256 withdrawBlock
);
/// Emitted when owner withdraws relayManager funds
event StakeWithdrawn(
address indexed relayManager,
address indexed owner,
uint256 amount
);
/// Emitted when an authorized Relay Hub penalizes a relayManager
event StakePenalized(
address indexed relayManager,
address indexed beneficiary,
uint256 reward
);
event HubAuthorized(
address indexed relayManager,
address indexed relayHub
);
event HubUnauthorized(
address indexed relayManager,
address indexed relayHub,
uint256 removalBlock
);
event OwnerSet(
address indexed relayManager,
address indexed owner
);
/// @param stake - amount of ether staked for this relay
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
/// @param withdrawBlock - first block number 'withdraw' will be callable, or zero if the unlock has not been called
/// @param owner - address that receives revenue and manages relayManager's stake
struct StakeInfo {
uint256 stake;
uint256 unstakeDelay;
uint256 withdrawBlock;
address payable owner;
}
struct RelayHubInfo {
uint256 removalBlock;
}
/// Set the owner of a Relay Manager. Called only by the RelayManager itself.
/// Note that owners cannot transfer ownership - if the entry already exists, reverts.
/// @param owner - owner of the relay (as configured off-chain)
function setRelayManagerOwner(address payable owner) external;
/// Only the owner can call this function. If the entry does not exist, reverts.
/// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs
/// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock'
function stakeForRelayManager(address relayManager, uint256 unstakeDelay) external payable;
function unlockStake(address relayManager) external;
function withdrawStake(address relayManager) external;
function authorizeHubByOwner(address relayManager, address relayHub) external;
function authorizeHubByManager(address relayHub) external;
function unauthorizeHubByOwner(address relayManager, address relayHub) external;
function unauthorizeHubByManager(address relayHub) external;
function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay)
external
view
returns (bool);
/// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way.
/// @param relayManager - entry to penalize
/// @param beneficiary - address that receives half of the penalty amount
/// @param amount - amount to withdraw from stake
function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external;
function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo);
function maxUnstakeDelay() external view returns (uint256);
function versionSM() external view returns (string memory);
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
interface IVersionRegistry {
//event emitted whenever a version is added
event VersionAdded(bytes32 indexed id, bytes32 version, string value, uint time);
//event emitted whenever a version is canceled
event VersionCanceled(bytes32 indexed id, bytes32 version, string reason);
/**
* add a version
* @param id the object-id to add a version (32-byte string)
* @param version the new version to add (32-byte string)
* @param value value to attach to this version
*/
function addVersion(bytes32 id, bytes32 version, string calldata value) external;
/**
* cancel a version.
*/
function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external;
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
import "@opengsn/contracts/src/BaseRelayRecipient.sol";
//make sure that "payable" function that uses _msgSender() still works
// (its not required to use _msgSender(), since the default function
// will never be called through GSN, but still, if someone uses it,
// it should work)
contract PayableWithEmit is BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.payablewithemit.irelayrecipient";
event Received(address sender, uint value, uint gasleft);
receive () external payable {
emit Received(_msgSender(), msg.value, gasleft());
}
//helper: send value to another contract
function doSend(address payable target) public payable {
uint before = gasleft();
// solhint-disable-next-line check-send-result
bool success = target.send(msg.value);
uint gasAfter = gasleft();
emit GasUsed(before-gasAfter, success);
}
event GasUsed(uint gasUsed, bool success);
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterConfigurableMisbehavior is TestPaymasterEverythingAccepted {
bool public withdrawDuringPostRelayedCall;
bool public withdrawDuringPreRelayedCall;
bool public returnInvalidErrorCode;
bool public revertPostRelayCall;
bool public outOfGasPre;
bool public revertPreRelayCall;
bool public revertPreRelayCallOnEvenBlocks;
bool public greedyAcceptanceBudget;
bool public expensiveGasLimits;
function setWithdrawDuringPostRelayedCall(bool val) public {
withdrawDuringPostRelayedCall = val;
}
function setWithdrawDuringPreRelayedCall(bool val) public {
withdrawDuringPreRelayedCall = val;
}
function setReturnInvalidErrorCode(bool val) public {
returnInvalidErrorCode = val;
}
function setRevertPostRelayCall(bool val) public {
revertPostRelayCall = val;
}
function setRevertPreRelayCall(bool val) public {
revertPreRelayCall = val;
}
function setRevertPreRelayCallOnEvenBlocks(bool val) public {
revertPreRelayCallOnEvenBlocks = val;
}
function setOutOfGasPre(bool val) public {
outOfGasPre = val;
}
function setGreedyAcceptanceBudget(bool val) public {
greedyAcceptanceBudget = val;
}
function setExpensiveGasLimits(bool val) public {
expensiveGasLimits = val;
}
// solhint-disable reason-string
// contains comments that are checked in tests
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
relayHubOnly
returns (bytes memory, bool) {
(signature, approvalData, maxPossibleGas);
if (outOfGasPre) {
uint i = 0;
while (true) {
i++;
}
}
require(!returnInvalidErrorCode, "invalid code");
if (withdrawDuringPreRelayedCall) {
withdrawAllBalance();
}
if (revertPreRelayCall) {
revert("You asked me to revert, remember?");
}
if (revertPreRelayCallOnEvenBlocks && block.number % 2 == 0) {
revert("You asked me to revert on even blocks, remember?");
}
_verifyForwarder(relayRequest);
return ("", trustRecipientRevert);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
relayHubOnly
{
(context, success, gasUseWithoutPost, relayData);
if (withdrawDuringPostRelayedCall) {
withdrawAllBalance();
}
if (revertPostRelayCall) {
revert("You asked me to revert, remember?");
}
}
/// leaving withdrawal public and unprotected
function withdrawAllBalance() public returns (uint256) {
require(address(relayHub) != address(0), "relay hub address not set");
uint256 balance = relayHub.balanceOf(address(this));
relayHub.withdraw(balance, address(this));
return balance;
}
IPaymaster.GasAndDataLimits private limits = super.getGasAndDataLimits();
function getGasAndDataLimits()
public override view
returns (IPaymaster.GasAndDataLimits memory) {
if (expensiveGasLimits) {
uint sum;
//memory access is 700gas, so we waste ~50000
for ( int i=0; i<60000; i+=700 ) {
sum = sum + limits.acceptanceBudget;
}
}
if (greedyAcceptanceBudget) {
return IPaymaster.GasAndDataLimits(limits.acceptanceBudget * 9, limits.preRelayedCallGasLimit, limits.postRelayedCallGasLimit,
limits.calldataSizeLimit);
}
return limits;
}
bool private trustRecipientRevert;
function setGasLimits(uint acceptanceBudget, uint preRelayedCallGasLimit, uint postRelayedCallGasLimit) public {
limits = IPaymaster.GasAndDataLimits(
acceptanceBudget,
preRelayedCallGasLimit,
postRelayedCallGasLimit,
limits.calldataSizeLimit
);
}
function setTrustRecipientRevert(bool on) public {
trustRecipientRevert = on;
}
// solhint-disable-next-line no-empty-blocks
receive() external override payable {}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../forwarder/IForwarder.sol";
import "../BasePaymaster.sol";
contract TestPaymasterEverythingAccepted is BasePaymaster {
function versionPaymaster() external view override virtual returns (string memory){
return "2.2.0+opengsn.test-pea.ipaymaster";
}
event SampleRecipientPreCall();
event SampleRecipientPostCall(bool success, uint actualCharge);
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
virtual
returns (bytes memory, bool) {
(signature);
_verifyForwarder(relayRequest);
(approvalData, maxPossibleGas);
emit SampleRecipientPreCall();
return ("no revert here",false);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
virtual
{
(context, gasUseWithoutPost, relayData);
emit SampleRecipientPostCall(success, gasUseWithoutPost);
}
function deposit() public payable {
require(address(relayHub) != address(0), "relay hub address not set");
relayHub.depositFor{value:msg.value}(address(this));
}
function withdrawAll(address payable destination) public {
uint256 amount = relayHub.balanceOf(address(this));
withdrawRelayHubDepositTo(amount, destination);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterOwnerSignature is TestPaymasterEverythingAccepted {
using ECDSA for bytes32;
/**
* This demonstrates how dapps can provide an off-chain signatures to relayed transactions.
*/
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
view
override
returns (bytes memory, bool) {
(signature, maxPossibleGas);
_verifyForwarder(relayRequest);
address signer =
keccak256(abi.encodePacked("I approve", relayRequest.request.from))
.toEthSignedMessageHash()
.recover(approvalData);
require(signer == owner(), "test: not approved");
return ("",false);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterPreconfiguredApproval is TestPaymasterEverythingAccepted {
bytes public expectedApprovalData;
function setExpectedApprovalData(bytes memory val) public {
expectedApprovalData = val;
}
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
view
override
returns (bytes memory, bool) {
(relayRequest, signature, approvalData, maxPossibleGas);
_verifyForwarder(relayRequest);
require(keccak256(expectedApprovalData) == keccak256(approvalData),
string(abi.encodePacked(
"test: unexpected approvalData: '", approvalData, "' instead of '", expectedApprovalData, "'")));
return ("",false);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterStoreContext is TestPaymasterEverythingAccepted {
event SampleRecipientPreCallWithValues(
address relay,
address from,
bytes encodedFunction,
uint256 baseRelayFee,
uint256 pctRelayFee,
uint256 gasPrice,
uint256 gasLimit,
bytes approvalData,
uint256 maxPossibleGas
);
event SampleRecipientPostCallWithValues(
string context
);
/**
* This demonstrates how preRelayedCall can return 'context' data for reuse in postRelayedCall.
*/
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
returns (bytes memory, bool) {
(signature, approvalData, maxPossibleGas);
_verifyForwarder(relayRequest);
emit SampleRecipientPreCallWithValues(
relayRequest.relayData.relayWorker,
relayRequest.request.from,
relayRequest.request.data,
relayRequest.relayData.baseRelayFee,
relayRequest.relayData.pctRelayFee,
relayRequest.relayData.gasPrice,
relayRequest.request.gas,
approvalData,
maxPossibleGas);
return ("context passed from preRelayedCall to postRelayedCall",false);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
relayHubOnly
{
(context, success, gasUseWithoutPost, relayData);
emit SampleRecipientPostCallWithValues(string(context));
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "./TestPaymasterEverythingAccepted.sol";
contract TestPaymasterVariableGasLimits is TestPaymasterEverythingAccepted {
string public override versionPaymaster = "2.2.0+opengsn.test-vgl.ipaymaster";
event SampleRecipientPreCallWithValues(
uint256 gasleft,
uint256 maxPossibleGas
);
event SampleRecipientPostCallWithValues(
uint256 gasleft,
uint256 gasUseWithoutPost
);
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
returns (bytes memory, bool) {
(signature, approvalData);
_verifyForwarder(relayRequest);
emit SampleRecipientPreCallWithValues(
gasleft(), maxPossibleGas);
return ("", false);
}
function postRelayedCall(
bytes calldata context,
bool success,
uint256 gasUseWithoutPost,
GsnTypes.RelayData calldata relayData
)
external
override
relayHubOnly
{
(context, success, gasUseWithoutPost, relayData);
emit SampleRecipientPostCallWithValues(gasleft(), gasUseWithoutPost);
}
}
/* solhint-disable avoid-tx-origin */
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
import "../utils/GsnUtils.sol";
import "../BaseRelayRecipient.sol";
import "./TestPaymasterConfigurableMisbehavior.sol";
contract TestRecipient is BaseRelayRecipient {
string public override versionRecipient = "2.2.0+opengsn.test.irelayrecipient";
constructor(address forwarder) {
setTrustedForwarder(forwarder);
}
function getTrustedForwarder() public view returns(address) {
return trustedForwarder;
}
function setTrustedForwarder(address forwarder) internal {
trustedForwarder = forwarder;
}
event Reverting(string message);
function testRevert() public {
require(address(this) == address(0), "always fail");
emit Reverting("if you see this revert failed...");
}
address payable public paymaster;
function setWithdrawDuringRelayedCall(address payable _paymaster) public {
paymaster = _paymaster;
}
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
event SampleRecipientEmitted(string message, address realSender, address msgSender, address origin, uint256 msgValue, uint256 gasLeft, uint256 balance);
function emitMessage(string memory message) public payable returns (string memory) {
uint256 gasLeft = gasleft();
if (paymaster != address(0)) {
withdrawAllBalance();
}
emit SampleRecipientEmitted(message, _msgSender(), msg.sender, tx.origin, msg.value, gasLeft, address(this).balance);
return "emitMessage return value";
}
function withdrawAllBalance() public {
TestPaymasterConfigurableMisbehavior(paymaster).withdrawAllBalance();
}
// solhint-disable-next-line no-empty-blocks
function dontEmitMessage(string calldata message) public {}
function emitMessageNoParams() public {
emit SampleRecipientEmitted("Method with no parameters", _msgSender(), msg.sender, tx.origin, 0, gasleft(), address(this).balance);
}
//return (or revert) with a string in the given length
function checkReturnValues(uint len, bool doRevert) public view returns (string memory) {
(this);
string memory mesg = "this is a long message that we are going to return a small part from. we don't use a loop since we want a fixed gas usage of the method itself.";
require( bytes(mesg).length>=len, "invalid len: too large");
/* solhint-disable no-inline-assembly */
//cut the msg at that length
assembly { mstore(mesg, len) }
require(!doRevert, mesg);
return mesg;
}
//function with no return value (also test revert with no msg.
function checkNoReturnValues(bool doRevert) public view {
(this);
/* solhint-disable reason-string*/
require(!doRevert);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../utils/RelayHubValidator.sol";
contract TestRelayHubValidator {
//for testing purposes, we must be called from a method with same param signature as RelayCall
function dummyRelayCall(
uint, //paymasterMaxAcceptanceBudget,
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint //externalGasLimit
) external pure {
RelayHubValidator.verifyTransactionPacking(relayRequest, signature, approvalData);
}
// helper method for verifyTransactionPacking
function dynamicParamSize(bytes calldata buf) external pure returns (uint) {
return RelayHubValidator.dynamicParamSize(buf);
}
}
/* solhint-disable avoid-tx-origin */
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../interfaces/IRelayHub.sol";
contract TestRelayWorkerContract {
function relayCall(
IRelayHub hub,
uint maxAcceptanceBudget,
GsnTypes.RelayRequest memory relayRequest,
bytes memory signature,
uint externalGasLimit)
public
{
hub.relayCall{gas:externalGasLimit}(maxAcceptanceBudget, relayRequest, signature, "", externalGasLimit);
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
import "../utils/GsnEip712Library.sol";
import "../utils/GsnUtils.sol";
contract TestUtil {
function libRelayRequestName() public pure returns (string memory) {
return GsnEip712Library.RELAY_REQUEST_NAME;
}
function libRelayRequestType() public pure returns (string memory) {
return string(GsnEip712Library.RELAY_REQUEST_TYPE);
}
function libRelayRequestTypeHash() public pure returns (bytes32) {
return GsnEip712Library.RELAY_REQUEST_TYPEHASH;
}
function libRelayRequestSuffix() public pure returns (string memory) {
return GsnEip712Library.RELAY_REQUEST_SUFFIX;
}
//helpers for test to call the library funcs:
function callForwarderVerify(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature
)
external
view {
GsnEip712Library.verify(relayRequest, signature);
}
function callForwarderVerifyAndCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature
)
external
returns (
bool success,
bytes memory ret
) {
bool forwarderSuccess;
(forwarderSuccess, success, ret) = GsnEip712Library.execute(relayRequest, signature);
if ( !forwarderSuccess) {
GsnUtils.revertWithData(ret);
}
emit Called(success, success == false ? ret : bytes(""));
}
event Called(bool success, bytes error);
function splitRequest(
GsnTypes.RelayRequest calldata relayRequest
)
external
pure
returns (
bytes32 typeHash,
bytes memory suffixData
) {
(suffixData) = GsnEip712Library.splitRequest(relayRequest);
typeHash = GsnEip712Library.RELAY_REQUEST_TYPEHASH;
}
function libDomainSeparator(address forwarder) public pure returns (bytes32) {
return GsnEip712Library.domainSeparator(forwarder);
}
function libGetChainID() public pure returns (uint256) {
return GsnEip712Library.getChainID();
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
import "../interfaces/IRelayRecipient.sol";
import "../forwarder/IForwarder.sol";
import "./GsnUtils.sol";
/**
* Bridge Library to map GSN RelayRequest into a call of a Forwarder
*/
library GsnEip712Library {
// maximum length of return value/revert reason for 'execute' method. Will truncate result if exceeded.
uint256 private constant MAX_RETURN_SIZE = 1024;
//copied from Forwarder (can't reference string constants even from another library)
string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data,uint256 validUntil";
bytes public constant RELAYDATA_TYPE = "RelayData(uint256 gasPrice,uint256 pctRelayFee,uint256 baseRelayFee,address relayWorker,address paymaster,address forwarder,bytes paymasterData,uint256 clientId)";
string public constant RELAY_REQUEST_NAME = "RelayRequest";
string public constant RELAY_REQUEST_SUFFIX = string(abi.encodePacked("RelayData relayData)", RELAYDATA_TYPE));
bytes public constant RELAY_REQUEST_TYPE = abi.encodePacked(
RELAY_REQUEST_NAME,"(",GENERIC_PARAMS,",", RELAY_REQUEST_SUFFIX);
bytes32 public constant RELAYDATA_TYPEHASH = keccak256(RELAYDATA_TYPE);
bytes32 public constant RELAY_REQUEST_TYPEHASH = keccak256(RELAY_REQUEST_TYPE);
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
function splitRequest(
GsnTypes.RelayRequest calldata req
)
internal
pure
returns (
bytes memory suffixData
) {
suffixData = abi.encode(
hashRelayData(req.relayData));
}
//verify that the recipient trusts the given forwarder
// MUST be called by paymaster
function verifyForwarderTrusted(GsnTypes.RelayRequest calldata relayRequest) internal view {
(bool success, bytes memory ret) = relayRequest.request.to.staticcall(
abi.encodeWithSelector(
IRelayRecipient.isTrustedForwarder.selector, relayRequest.relayData.forwarder
)
);
require(success, "isTrustedForwarder: reverted");
require(ret.length == 32, "isTrustedForwarder: bad response");
require(abi.decode(ret, (bool)), "invalid forwarder for recipient");
}
function verifySignature(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view {
(bytes memory suffixData) = splitRequest(relayRequest);
bytes32 _domainSeparator = domainSeparator(relayRequest.relayData.forwarder);
IForwarder forwarder = IForwarder(payable(relayRequest.relayData.forwarder));
forwarder.verify(relayRequest.request, _domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature);
}
function verify(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view {
verifyForwarderTrusted(relayRequest);
verifySignature(relayRequest, signature);
}
function execute(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal returns (bool forwarderSuccess, bool callSuccess, bytes memory ret) {
(bytes memory suffixData) = splitRequest(relayRequest);
bytes32 _domainSeparator = domainSeparator(relayRequest.relayData.forwarder);
/* solhint-disable-next-line avoid-low-level-calls */
(forwarderSuccess, ret) = relayRequest.relayData.forwarder.call(
abi.encodeWithSelector(IForwarder.execute.selector,
relayRequest.request, _domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature
));
if ( forwarderSuccess ) {
//decode return value of execute:
(callSuccess, ret) = abi.decode(ret, (bool, bytes));
}
truncateInPlace(ret);
}
//truncate the given parameter (in-place) if its length is above the given maximum length
// do nothing otherwise.
//NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter.
function truncateInPlace(bytes memory data) internal pure {
MinLibBytes.truncateInPlace(data, MAX_RETURN_SIZE);
}
function domainSeparator(address forwarder) internal pure returns (bytes32) {
return hashDomain(EIP712Domain({
name : "GSN Relayed Transaction",
version : "2",
chainId : getChainID(),
verifyingContract : forwarder
}));
}
function getChainID() internal pure returns (uint256 id) {
/* solhint-disable no-inline-assembly */
assembly {
id := chainid()
}
}
function hashDomain(EIP712Domain memory req) internal pure returns (bytes32) {
return keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(req.name)),
keccak256(bytes(req.version)),
req.chainId,
req.verifyingContract));
}
function hashRelayData(GsnTypes.RelayData calldata req) internal pure returns (bytes32) {
return keccak256(abi.encode(
RELAYDATA_TYPEHASH,
req.gasPrice,
req.pctRelayFee,
req.baseRelayFee,
req.relayWorker,
req.paymaster,
req.forwarder,
keccak256(req.paymasterData),
req.clientId
));
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
import "../forwarder/IForwarder.sol";
interface GsnTypes {
/// @notice gasPrice, pctRelayFee and baseRelayFee must be validated inside of the paymaster's preRelayedCall in order not to overpay
struct RelayData {
uint256 gasPrice;
uint256 pctRelayFee;
uint256 baseRelayFee;
address relayWorker;
address paymaster;
address forwarder;
bytes paymasterData;
uint256 clientId;
}
//note: must start with the ForwardRequest to be an extension of the generic forwarder
struct RelayRequest {
IForwarder.ForwardRequest request;
RelayData relayData;
}
}
/* solhint-disable no-inline-assembly */
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
import "../utils/MinLibBytes.sol";
library GsnUtils {
/**
* extract method sig from encoded function call
*/
function getMethodSig(bytes memory msgData) internal pure returns (bytes4) {
return MinLibBytes.readBytes4(msgData, 0);
}
/**
* extract parameter from encoded-function block.
* see: https://solidity.readthedocs.io/en/develop/abi-spec.html#formal-specification-of-the-encoding
* the return value should be casted to the right type (uintXXX/bytesXXX/address/bool/enum)
*/
function getParam(bytes memory msgData, uint index) internal pure returns (uint) {
return MinLibBytes.readUint256(msgData, 4 + index * 32);
}
//re-throw revert with the same revert data.
function revertWithData(bytes memory data) internal pure {
assembly {
revert(add(data,32), mload(data))
}
}
}
// SPDX-License-Identifier: MIT
// minimal bytes manipulation required by GSN
// a minimal subset from 0x/LibBytes
/* solhint-disable no-inline-assembly */
pragma solidity >=0.7.6;
library MinLibBytes {
//truncate the given parameter (in-place) if its length is above the given maximum length
// do nothing otherwise.
//NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter.
function truncateInPlace(bytes memory data, uint256 maxlen) internal pure {
if (data.length > maxlen) {
assembly { mstore(data, maxlen) }
}
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require (b.length >= index + 20, "readAddress: data too short");
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(b.length >= index + 32, "readBytes32: data too short" );
// Read the bytes32 from array memory
assembly {
result := mload(add(b, add(index,32)))
}
return result;
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(b.length >= index + 4, "readBytes4: data too short");
// Read the bytes4 from array memory
assembly {
result := mload(add(b, add(index,32)))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
}
// SPDX-License-Identifier:APACHE-2.0
/*
* Taken from https://github.com/hamdiallam/Solidity-RLP
*/
/* solhint-disable */
pragma solidity ^0.7.6;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
using RLPReader for bytes;
using RLPReader for uint;
using RLPReader for RLPReader.RLPItem;
// helper function to decode rlp encoded legacy ethereum transaction
/*
* @param rawTransaction RLP encoded legacy ethereum transaction rlp([nonce, gasPrice, gasLimit, to, value, data]))
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeLegacyTransaction(bytes calldata rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes());
}
/*
* @param rawTransaction format: 0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, access_list]))
* @return tuple (nonce,gasPrice,gasLimit,to,value,data)
*/
function decodeTransactionType1(bytes calldata rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){
bytes memory payload = rawTransaction[1:rawTransaction.length];
RLPReader.RLPItem[] memory values = payload.toRlpItem().toList(); // must convert to an rlpItem first!
return (values[1].toUint(), values[2].toUint(), values[3].toUint(), values[4].toAddress(), values[5].toUint(), values[6].toBytes());
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
if (item.length == 0)
return RLPItem(0, 0);
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) {
require(isList(item), "isList failed");
uint items = numItems(item);
result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
}
/*
* Helpers
*/
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) internal pure returns (uint) {
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr);
// skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) internal pure returns (uint len) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 1;
else if (byte0 < STRING_LONG_START)
return byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
len := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
return byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
len := add(dataLen, add(byteLen, 1))
}
}
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) internal pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte");
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix according to RLP spec
require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less");
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint memPtr = item.memPtr + offset;
uint result;
assembly {
result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
// data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) internal pure {
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.5;
pragma abicoder v2;
import "../utils/GsnTypes.sol";
library RelayHubValidator {
// validate that encoded relayCall is properly packed without any extra bytes
function verifyTransactionPacking(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData
) internal pure {
// abicoder v2: https://docs.soliditylang.org/en/latest/abi-spec.html
// each static param/member is 1 word
// struct (with dynamic members) has offset to struct which is 1 word
// dynamic member is 1 word offset to actual value, which is 1-word length and ceil(length/32) words for data
// relayCall has 5 method params,
// relayRequest: 2 members
// relayData 8 members
// ForwardRequest: 7 members
// total 22 32-byte words if all dynamic params are zero-length.
uint expectedMsgDataLen = 4 + 22 * 32 +
dynamicParamSize(signature) +
dynamicParamSize(approvalData) +
dynamicParamSize(relayRequest.request.data) +
dynamicParamSize(relayRequest.relayData.paymasterData);
require(signature.length <= 65, "invalid signature length");
require(expectedMsgDataLen == msg.data.length, "extra msg.data bytes" );
}
// helper method for verifyTransactionPacking:
// size (in bytes) of the given "bytes" parameter. size include the length (32-byte word),
// and actual data size, rounded up to full 32-byte words
function dynamicParamSize(bytes calldata buf) internal pure returns (uint) {
return 32 + ((buf.length + 31) & uint(~31));
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.7.6;
// solhint-disable not-rely-on-time
import "../interfaces/IVersionRegistry.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract VersionRegistry is IVersionRegistry, Ownable {
function addVersion(bytes32 id, bytes32 version, string calldata value) external override onlyOwner {
require(id != bytes32(0), "missing id");
require(version != bytes32(0), "missing version");
emit VersionAdded(id, version, value, block.timestamp);
}
function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external override onlyOwner {
emit VersionCanceled(id, version, reason);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () /*internal*/ {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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
// solhint-disable no-inline-assembly
pragma solidity >=0.7.6;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
return msg.data[0:msg.data.length-20];
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier:MIT
pragma solidity >=0.7.6;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise (if the call was made directly and not through the forwarder), return `msg.data`
* should be used in the contract instead of msg.data, where this difference matters.
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
| function with no return value (also test revert with no msg. | function checkNoReturnValues(bool doRevert) public view {
(this);
require(!doRevert);
| 45,760 | [
1,
915,
598,
1158,
327,
460,
261,
31144,
1842,
15226,
598,
1158,
1234,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
866,
2279,
990,
1972,
12,
6430,
741,
426,
1097,
13,
1071,
1476,
288,
203,
3639,
261,
2211,
1769,
203,
3639,
2583,
12,
5,
2896,
426,
1097,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-16
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/upgradeability/EternalStorage.sol
pragma solidity 0.7.5;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File: contracts/upgradeable_contracts/Initializable.sol
pragma solidity 0.7.5;
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
// File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
pragma solidity 0.7.5;
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
// File: contracts/upgradeable_contracts/Upgradeable.sol
pragma solidity 0.7.5;
contract Upgradeable {
// Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner());
_;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.7.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/upgradeable_contracts/Sacrifice.sol
pragma solidity 0.7.5;
contract Sacrifice {
constructor(address payable _recipient) payable {
selfdestruct(_recipient);
}
}
// File: contracts/libraries/AddressHelper.sol
pragma solidity 0.7.5;
/**
* @title AddressHelper
* @dev Helper methods for Address type.
*/
library AddressHelper {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address payable _receiver, uint256 _value) internal {
if (!(_receiver).send(_value)) {
new Sacrifice{ value: _value }(_receiver);
}
}
}
// File: contracts/upgradeable_contracts/Claimable.sol
pragma solidity 0.7.5;
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for IERC20;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
AddressHelper.safeSendValue(payable(_to), value);
}
/**
* @dev Internal function for withdrawing all tokens of some particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(_to, balance);
}
}
// File: contracts/upgradeable_contracts/components/bridged/BridgedTokensRegistry.sol
pragma solidity 0.7.5;
/**
* @title BridgedTokensRegistry
* @dev Functionality for keeping track of registered bridged token pairs.
*/
contract BridgedTokensRegistry is EternalStorage {
event NewTokenRegistered(address indexed nativeToken, address indexed bridgedToken);
/**
* @dev Retrieves address of the bridged token contract associated with a specific native token contract on the other side.
* @param _nativeToken address of the native token contract on the other side.
* @return address of the deployed bridged token contract.
*/
function bridgedTokenAddress(address _nativeToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))];
}
/**
* @dev Retrieves address of the native token contract associated with a specific bridged token contract.
* @param _bridgedToken address of the created bridged token contract on this side.
* @return address of the native token contract on the other side of the bridge.
*/
function nativeTokenAddress(address _bridgedToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))];
}
/**
* @dev Internal function for updating a pair of addresses for the bridged token.
* @param _nativeToken address of the native token contract on the other side.
* @param _bridgedToken address of the created bridged token contract on this side.
*/
function _setTokenAddressPair(address _nativeToken, address _bridgedToken) internal {
addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))] = _bridgedToken;
addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))] = _nativeToken;
emit NewTokenRegistered(_nativeToken, _bridgedToken);
}
}
// File: contracts/upgradeable_contracts/components/native/NativeTokensRegistry.sol
pragma solidity 0.7.5;
/**
* @title NativeTokensRegistry
* @dev Functionality for keeping track of registered native tokens.
*/
contract NativeTokensRegistry is EternalStorage {
/**
* @dev Checks if for a given native token, the deployment of its bridged alternative was already acknowledged.
* @param _token address of native token contract.
* @return true, if bridged token was already deployed.
*/
function isBridgedTokenDeployAcknowledged(address _token) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))];
}
/**
* @dev Acknowledges the deployment of bridged token contract on the other side.
* @param _token address of native token contract.
*/
function _ackBridgedTokenDeploy(address _token) internal {
if (!boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))]) {
boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))] = true;
}
}
}
// File: contracts/upgradeable_contracts/components/native/MediatorBalanceStorage.sol
pragma solidity 0.7.5;
/**
* @title MediatorBalanceStorage
* @dev Functionality for storing expected mediator balance for native tokens.
*/
contract MediatorBalanceStorage is EternalStorage {
/**
* @dev Tells the expected token balance of the contract.
* @param _token address of token contract.
* @return the current tracked token balance of the contract.
*/
function mediatorBalance(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))];
}
/**
* @dev Updates expected token balance of the contract.
* @param _token address of token contract.
* @param _balance the new token balance of the contract.
*/
function _setMediatorBalance(address _token, uint256 _balance) internal {
uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance;
}
}
// File: contracts/interfaces/IERC677.sol
pragma solidity 0.7.5;
interface IERC677 is IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// File: contracts/libraries/Bytes.sol
pragma solidity 0.7.5;
/**
* @title Bytes
* @dev Helper methods to transform bytes to other solidity types.
*/
library Bytes {
/**
* @dev Truncate bytes array if its size is more than 20 bytes.
* NOTE: This function does not perform any checks on the received parameter.
* Make sure that the _bytes argument has a correct length, not less than 20 bytes.
* A case when _bytes has length less than 20 will lead to the undefined behaviour,
* since assembly will read data from memory that is not related to the _bytes argument.
* @param _bytes to be converted to address type
* @return addr address included in the firsts 20 bytes of the bytes array in parameter.
*/
function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
// File: contracts/upgradeable_contracts/ReentrancyGuard.sol
pragma solidity 0.7.5;
contract ReentrancyGuard {
function lock() internal view returns (bool res) {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock"))
}
}
function setLock(bool _lock) internal {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock"))
}
}
}
// File: contracts/upgradeable_contracts/Ownable.sol
pragma solidity 0.7.5;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_onlyOwner();
_;
}
/**
* @dev Internal function for reducing onlyOwner modifier bytecode overhead.
*/
function _onlyOwner() internal view {
require(msg.sender == owner());
}
/**
* @dev Throws if called through proxy by any account other than contract itself or an upgradeability owner.
*/
modifier onlyRelevantSender() {
(bool isProxy, bytes memory returnData) =
address(this).staticcall(abi.encodeWithSelector(UPGRADEABILITY_OWNER));
require(
!isProxy || // covers usage without calling through storage proxy
(returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[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) external onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
// File: contracts/interfaces/IAMB.sol
pragma solidity 0.7.5;
interface IAMB {
event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData);
event UserRequestForSignature(bytes32 indexed messageId, bytes encodedData);
event AffirmationCompleted(
address indexed sender,
address indexed executor,
bytes32 indexed messageId,
bool status
);
event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status);
function messageSender() external view returns (address);
function maxGasPerTx() external view returns (uint256);
function transactionHash() external view returns (bytes32);
function messageId() external view returns (bytes32);
function messageSourceChainId() external view returns (bytes32);
function messageCallStatus(bytes32 _messageId) external view returns (bool);
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
function failedMessageSender(bytes32 _messageId) external view returns (address);
function requireToPassMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function requireToConfirmMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function sourceChainId() external view returns (uint256);
function destinationChainId() external view returns (uint256);
}
// File: contracts/upgradeable_contracts/BasicAMBMediator.sol
pragma solidity 0.7.5;
/**
* @title BasicAMBMediator
* @dev Basic storage and methods needed by mediators to interact with AMB bridge.
*/
abstract contract BasicAMBMediator is Ownable {
bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract"))
bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract"))
/**
* @dev Throws if caller on the other side is not an associated mediator.
*/
modifier onlyMediator {
_onlyMediator();
_;
}
/**
* @dev Internal function for reducing onlyMediator modifier bytecode overhead.
*/
function _onlyMediator() internal view {
IAMB bridge = bridgeContract();
require(msg.sender == address(bridge));
require(bridge.messageSender() == mediatorContractOnOtherSide());
}
/**
* @dev Sets the AMB bridge contract address. Only the owner can call this method.
* @param _bridgeContract the address of the bridge contract.
*/
function setBridgeContract(address _bridgeContract) external onlyOwner {
_setBridgeContract(_bridgeContract);
}
/**
* @dev Sets the mediator contract address from the other network. Only the owner can call this method.
* @param _mediatorContract the address of the mediator contract.
*/
function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
_setMediatorContractOnOtherSide(_mediatorContract);
}
/**
* @dev Get the AMB interface for the bridge contract address
* @return AMB interface for the bridge contract address
*/
function bridgeContract() public view returns (IAMB) {
return IAMB(addressStorage[BRIDGE_CONTRACT]);
}
/**
* @dev Tells the mediator contract address from the other network.
* @return the address of the mediator contract.
*/
function mediatorContractOnOtherSide() public view virtual returns (address) {
return addressStorage[MEDIATOR_CONTRACT];
}
/**
* @dev Stores a valid AMB bridge contract address.
* @param _bridgeContract the address of the bridge contract.
*/
function _setBridgeContract(address _bridgeContract) internal {
require(Address.isContract(_bridgeContract));
addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
}
/**
* @dev Stores the mediator contract address from the other network.
* @param _mediatorContract the address of the mediator contract.
*/
function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
}
/**
* @dev Tells the id of the message originated on the other network.
* @return the id of the message originated on the other network.
*/
function messageId() internal view returns (bytes32) {
return bridgeContract().messageId();
}
/**
* @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.
* @return the maximum gas limit value.
*/
function maxGasPerTx() internal view returns (uint256) {
return bridgeContract().maxGasPerTx();
}
function _passMessage(bytes memory _data, bool _useOracleLane) internal virtual returns (bytes32);
}
// File: contracts/upgradeable_contracts/components/common/TokensRelayer.sol
pragma solidity 0.7.5;
/**
* @title TokensRelayer
* @dev Functionality for bridging multiple tokens to the other side of the bridge.
*/
abstract contract TokensRelayer is BasicAMBMediator, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC677;
/**
* @dev ERC677 transfer callback function.
* @param _from address of tokens sender.
* @param _value amount of transferred tokens.
* @param _data additional transfer data, can be used for passing alternative receiver address.
*/
function onTokenTransfer(
address _from,
uint256 _value,
bytes memory _data
) external returns (bool) {
if (!lock()) {
bytes memory data = new bytes(0);
address receiver = _from;
if (_data.length >= 20) {
receiver = Bytes.bytesToAddress(_data);
if (_data.length > 20) {
assembly {
let size := sub(mload(_data), 20)
data := add(_data, 20)
mstore(data, size)
}
}
}
bridgeSpecificActionsOnTokenTransfer(msg.sender, _from, receiver, _value, data);
}
return true;
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(
IERC677 token,
address _receiver,
uint256 _value
) external {
_relayTokens(token, _receiver, _value, new bytes(0));
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(IERC677 token, uint256 _value) external {
_relayTokens(token, msg.sender, _value, new bytes(0));
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
* @param _data additional transfer data to be used on the other side.
*/
function relayTokensAndCall(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) external {
_relayTokens(token, _receiver, _value, _data);
}
/**
* @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract
* and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network.
* The user should first call Approve method of the ERC677 token.
* @param token bridge token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
* @param _data additional transfer data to be used on the other side.
*/
function _relayTokens(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) internal {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
uint256 balanceBefore = token.balanceOf(address(this));
setLock(true);
token.safeTransferFrom(msg.sender, address(this), _value);
setLock(false);
uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore);
require(balanceDiff <= _value);
bridgeSpecificActionsOnTokenTransfer(address(token), msg.sender, _receiver, balanceDiff, _data);
}
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual;
}
// File: contracts/upgradeable_contracts/VersionableBridge.sol
pragma solidity 0.7.5;
interface VersionableBridge {
function getBridgeInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
);
function getBridgeMode() external pure returns (bytes4);
}
// File: contracts/upgradeable_contracts/components/common/OmnibridgeInfo.sol
pragma solidity 0.7.5;
/**
* @title OmnibridgeInfo
* @dev Functionality for versioning Omnibridge mediator.
*/
contract OmnibridgeInfo is VersionableBridge {
event TokensBridgingInitiated(
address indexed token,
address indexed sender,
uint256 value,
bytes32 indexed messageId
);
event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId);
/**
* @dev Tells the bridge interface version that this contract supports.
* @return major value of the version
* @return minor value of the version
* @return patch value of the version
*/
function getBridgeInterfacesVersion()
external
pure
override
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
// The patch version increased by 1 to reflect difference from
// the original contract: minting of STAKE token is disabled
return (3, 0, 1);
}
/**
* @dev Tells the bridge mode that this contract supports.
* @return _data 4 bytes representing the bridge mode
*/
function getBridgeMode() external pure override returns (bytes4 _data) {
return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb")))
}
}
// File: contracts/upgradeable_contracts/components/common/TokensBridgeLimits.sol
pragma solidity 0.7.5;
/**
* @title TokensBridgeLimits
* @dev Functionality for keeping track of bridging limits for multiple tokens.
*/
contract TokensBridgeLimits is EternalStorage, Ownable {
using SafeMath for uint256;
// token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens
event DailyLimitChanged(address indexed token, uint256 newLimit);
event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit);
/**
* @dev Checks if specified token was already bridged at least once.
* @param _token address of the token contract.
* @return true, if token address is address(0) or token was already bridged.
*/
function isTokenRegistered(address _token) public view returns (bool) {
return minPerTx(_token) > 0;
}
/**
* @dev Retrieves the total spent amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens sent through the bridge to the other side.
*/
function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))];
}
/**
* @dev Retrieves the total executed amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens received from the bridge from the other side.
*/
function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))];
}
/**
* @dev Retrieves current daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be sent through the bridge per day.
*/
function dailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))];
}
/**
* @dev Retrieves current execution daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be received from the bridge on the other side per day.
*/
function executionDailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))];
}
/**
* @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can be sent through the bridge in one transfer.
*/
function maxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))];
}
/**
* @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can received from the bridge on the other side in one transaction.
*/
function executionMaxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))];
}
/**
* @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return minimum amount on tokens that can be sent through the bridge in one transfer.
*/
function minPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))];
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be bridged.
*/
function withinLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount);
return
dailyLimit(address(0)) > 0 &&
dailyLimit(_token) >= nextLimit &&
_amount <= maxPerTx(_token) &&
_amount >= minPerTx(_token);
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured execution limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be processed and executed.
*/
function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount);
return
executionDailyLimit(address(0)) > 0 &&
executionDailyLimit(_token) >= nextLimit &&
_amount <= executionMaxPerTx(_token);
}
/**
* @dev Returns current day number.
* @return day number.
*/
function getCurrentDay() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp / 1 days;
}
/**
* @dev Updates daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the efault limit.
* @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit;
emit DailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit;
emit ExecutionDailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates minimum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _minPerTx minimum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit.
*/
function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token));
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx;
}
/**
* @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters.
* @param _token address of the token contract, or address(0) for the default limit.
* @return minimum of maxPerTx parameter and remaining daily quota.
*/
function maxAvailablePerTx(address _token) public view returns (uint256) {
uint256 _maxPerTx = maxPerTx(_token);
uint256 _dailyLimit = dailyLimit(_token);
uint256 _spent = totalSpentPerDay(_token, getCurrentDay());
uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
}
/**
* @dev Internal function for adding spent amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalSpentPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add(
_value
);
}
/**
* @dev Internal function for adding executed amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalExecutedPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay(
_token,
_day
)
.add(_value);
}
/**
* @dev Internal function for initializing limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ].
*/
function _setLimits(address _token, uint256[3] memory _limits) internal {
require(
_limits[2] > 0 && // minPerTx > 0
_limits[1] > _limits[2] && // maxPerTx > minPerTx
_limits[0] > _limits[1] // dailyLimit > maxPerTx
);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1];
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2];
emit DailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing execution limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ].
*/
function _setExecutionLimits(address _token, uint256[2] memory _limits) internal {
require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1];
emit ExecutionDailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing limits for some token relative to its decimals parameter.
* @param _token address of the token contract.
* @param _decimals token decimals parameter.
*/
function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal {
uint256 factor;
if (_decimals < 18) {
factor = 10**(18 - _decimals);
uint256 _minPerTx = minPerTx(address(0)).div(factor);
uint256 _maxPerTx = maxPerTx(address(0)).div(factor);
uint256 _dailyLimit = dailyLimit(address(0)).div(factor);
uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor);
uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor);
// such situation can happen when calculated limits relative to the token decimals are too low
// e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed.
// in this case, limits are raised to the default values
if (_minPerTx == 0) {
// Numbers 1, 100, 10000 are chosen in a semi-random way,
// so that any token with small decimals can still be bridged in some amounts.
// It is possible to override limits for the particular token later if needed.
_minPerTx = 1;
if (_maxPerTx <= _minPerTx) {
_maxPerTx = 100;
_executionMaxPerTx = 100;
if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) {
_dailyLimit = 10000;
_executionDailyLimit = 10000;
}
}
}
_setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]);
_setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]);
} else {
factor = 10**(_decimals - 18);
_setLimits(
_token,
[dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)]
);
_setExecutionLimits(
_token,
[executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)]
);
}
}
}
// File: contracts/upgradeable_contracts/components/common/BridgeOperationsStorage.sol
pragma solidity 0.7.5;
/**
* @title BridgeOperationsStorage
* @dev Functionality for storing processed bridged operations.
*/
abstract contract BridgeOperationsStorage is EternalStorage {
/**
* @dev Stores the bridged token of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _token bridged token address.
*/
function setMessageToken(bytes32 _messageId, address _token) internal {
addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
}
/**
* @dev Tells the bridged token address of a message sent to the AMB bridge.
* @return address of a token contract.
*/
function messageToken(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))];
}
/**
* @dev Stores the value of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _value amount of tokens bridged.
*/
function setMessageValue(bytes32 _messageId, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
}
/**
* @dev Tells the amount of tokens of a message sent to the AMB bridge.
* @return value representing amount of tokens.
*/
function messageValue(bytes32 _messageId) internal view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
}
/**
* @dev Stores the receiver of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _recipient receiver of the tokens bridged.
*/
function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
}
/**
* @dev Tells the receiver of a message sent to the AMB bridge.
* @return address of the receiver.
*/
function messageRecipient(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
}
}
// File: contracts/upgradeable_contracts/components/common/FailedMessagesProcessor.sol
pragma solidity 0.7.5;
/**
* @title FailedMessagesProcessor
* @dev Functionality for fixing failed bridging operations.
*/
abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage {
event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value);
/**
* @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to
* fix/roll back the transferred assets on the other network.
* @param _messageId id of the message which execution failed.
*/
function requestFailedMessageFix(bytes32 _messageId) external {
IAMB bridge = bridgeContract();
require(!bridge.messageCallStatus(_messageId));
require(bridge.failedMessageReceiver(_messageId) == address(this));
require(bridge.failedMessageSender(_messageId) == mediatorContractOnOtherSide());
bytes4 methodSelector = this.fixFailedMessage.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
_passMessage(data, true);
}
/**
* @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
* It uses the information stored by passMessage method when the assets were initially transferred
* @param _messageId id of the message which execution failed on the other network.
*/
function fixFailedMessage(bytes32 _messageId) public onlyMediator {
require(!messageFixed(_messageId));
address token = messageToken(_messageId);
address recipient = messageRecipient(_messageId);
uint256 value = messageValue(_messageId);
setMessageFixed(_messageId);
executeActionOnFixedTokens(token, recipient, value);
emit FailedMessageFixed(_messageId, token, recipient, value);
}
/**
* @dev Tells if a message sent to the AMB bridge has been fixed.
* @return bool indicating the status of the message.
*/
function messageFixed(bytes32 _messageId) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
}
/**
* @dev Sets that the message sent to the AMB bridge has been fixed.
* @param _messageId of the message sent to the bridge.
*/
function setMessageFixed(bytes32 _messageId) internal {
boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
}
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal virtual;
}
// File: contracts/upgradeability/Proxy.sol
pragma solidity 0.7.5;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view virtual returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
// solhint-disable-previous-line no-complex-fallback
address _impl = implementation();
require(_impl != address(0));
assembly {
/*
0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
memory. It's needed because we're going to write the return data of delegatecall to the
free memory slot.
*/
let ptr := mload(0x40)
/*
`calldatacopy` is copy calldatasize bytes from calldata
First argument is the destination to which data is copied(ptr)
Second argument specifies the start position of the copied data.
Since calldata is sort of its own unique location in memory,
0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
That's always going to be the zeroth byte of the function selector.
Third argument, calldatasize, specifies how much data will be copied.
calldata is naturally calldatasize bytes long (same thing as msg.data.length)
*/
calldatacopy(ptr, 0, calldatasize())
/*
delegatecall params explained:
gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
us the amount of gas still available to execution
_impl: address of the contract to delegate to
ptr: to pass copied data
calldatasize: loads the size of `bytes memory data`, same as msg.data.length
0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
these are set to 0, 0 so the output data will not be written to memory. The output
data will be read using `returndatasize` and `returdatacopy` instead.
result: This will be 0 if the call fails and 1 if it succeeds
*/
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
/*
*/
/*
ptr current points to the value stored at 0x40,
because we assigned it like ptr := mload(0x40).
Because we use 0x40 as a free memory pointer,
we want to make sure that the next time we want to allocate memory,
we aren't overwriting anything important.
So, by adding ptr and returndatasize,
we get a memory location beyond the end of the data we will be copying to ptr.
We place this in at 0x40, and any reads from 0x40 will now read from free memory
*/
mstore(0x40, add(ptr, returndatasize()))
/*
`returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
slot it will copy to, 0 means copy from the beginning of the return data, and size is
the amount of data to copy.
`returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
*/
returndatacopy(ptr, 0, returndatasize())
/*
if `result` is 0, revert.
if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
copied to `ptr` from the delegatecall return data
*/
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
}
// File: contracts/upgradeable_contracts/modules/factory/TokenProxy.sol
pragma solidity 0.7.5;
interface IPermittableTokenVersion {
function version() external pure returns (string memory);
}
/**
* @title TokenProxy
* @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract.
*/
contract TokenProxy is Proxy {
// storage layout is copied from PermittableToken.sol
string internal name;
string internal symbol;
uint8 internal decimals;
mapping(address => uint256) internal balances;
uint256 internal totalSupply;
mapping(address => mapping(address => uint256)) internal allowed;
address internal owner;
bool internal mintingFinished;
address internal bridgeContractAddr;
// string public constant version = "1";
bytes32 internal DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
mapping(address => uint256) internal nonces;
mapping(address => mapping(address => uint256)) internal expirations;
/**
* @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage.
* @param _tokenImage address of the token image used for mirroring all functions.
* @param _name token name.
* @param _symbol token symbol.
* @param _decimals token decimals.
* @param _chainId chain id for current network.
* @param _owner address of the owner for this contract.
*/
constructor(
address _tokenImage,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _chainId,
address _owner
) {
string memory version = IPermittableTokenVersion(_tokenImage).version();
assembly {
// EIP 1967
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage)
}
name = _name;
symbol = _symbol;
decimals = _decimals;
owner = _owner; // _owner == HomeOmnibridge/ForeignOmnibridge mediator
bridgeContractAddr = _owner;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes(version)),
_chainId,
address(this)
)
);
}
/**
* @dev Retrieves the implementation contract address, mirrored token image.
* @return impl token image address.
*/
function implementation() public view override returns (address impl) {
assembly {
impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
}
}
// File: contracts/upgradeable_contracts/modules/OwnableModule.sol
pragma solidity 0.7.5;
/**
* @title OwnableModule
* @dev Common functionality for multi-token extension non-upgradeable module.
*/
contract OwnableModule {
address public owner;
/**
* @dev Initializes this contract.
* @param _owner address of the owner that is allowed to perform additional actions on the particular module.
*/
constructor(address _owner) {
owner = _owner;
}
/**
* @dev Throws if sender is not the owner of this contract.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Changes the owner of this contract.
* @param _newOwner address of the new owner.
*/
function transferOwnership(address _newOwner) external onlyOwner {
owner = _newOwner;
}
}
// File: contracts/upgradeable_contracts/modules/factory/TokenFactory.sol
pragma solidity 0.7.5;
/**
* @title TokenFactory
* @dev Factory contract for deployment of new TokenProxy contracts.
*/
contract TokenFactory is OwnableModule {
address public tokenImage;
/**
* @dev Initializes this contract
* @param _owner of this factory contract.
* @param _tokenImage address of the token image contract that should be used for creation of new tokens.
*/
constructor(address _owner, address _tokenImage) OwnableModule(_owner) {
tokenImage = _tokenImage;
}
/**
* @dev Updates the address of the used token image contract.
* Only owner can call this method.
* @param _tokenImage address of the new token image used for further deployments.
*/
function setTokenImage(address _tokenImage) external onlyOwner {
require(Address.isContract(_tokenImage));
tokenImage = _tokenImage;
}
/**
* @dev Deploys a new TokenProxy contract, using saved token image contract as a template.
* @param _name deployed token name.
* @param _symbol deployed token symbol.
* @param _decimals deployed token decimals.
* @param _chainId chain id of the current environment.
* @return address of a newly created contract.
*/
function deploy(
string calldata _name,
string calldata _symbol,
uint8 _decimals,
uint256 _chainId
) external returns (address) {
return address(new TokenProxy(tokenImage, _name, _symbol, _decimals, _chainId, msg.sender));
}
}
// File: contracts/upgradeable_contracts/modules/factory/TokenFactoryConnector.sol
pragma solidity 0.7.5;
/**
* @title TokenFactoryConnector
* @dev Connectivity functionality for working with TokenFactory contract.
*/
contract TokenFactoryConnector is Ownable {
bytes32 internal constant TOKEN_FACTORY_CONTRACT =
0x269c5905f777ee6391c7a361d17039a7d62f52ba9fffeb98c5ade342705731a3; // keccak256(abi.encodePacked("tokenFactoryContract"))
/**
* @dev Updates an address of the used TokenFactory contract used for creating new tokens.
* @param _tokenFactory address of TokenFactory contract.
*/
function setTokenFactory(address _tokenFactory) external onlyOwner {
_setTokenFactory(_tokenFactory);
}
/**
* @dev Retrieves an address of the token factory contract.
* @return address of the TokenFactory contract.
*/
function tokenFactory() public view returns (TokenFactory) {
return TokenFactory(addressStorage[TOKEN_FACTORY_CONTRACT]);
}
/**
* @dev Internal function for updating an address of the token factory contract.
* @param _tokenFactory address of the deployed TokenFactory contract.
*/
function _setTokenFactory(address _tokenFactory) internal {
require(Address.isContract(_tokenFactory));
addressStorage[TOKEN_FACTORY_CONTRACT] = _tokenFactory;
}
}
// File: contracts/interfaces/IBurnableMintableERC677Token.sol
pragma solidity 0.7.5;
interface IBurnableMintableERC677Token is IERC677 {
function mint(address _to, uint256 _amount) external returns (bool);
function burn(uint256 _value) external;
function claimTokens(address _token, address _to) external;
}
// File: contracts/interfaces/IERC20Metadata.sol
pragma solidity 0.7.5;
interface IERC20Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/interfaces/IERC20Receiver.sol
pragma solidity 0.7.5;
interface IERC20Receiver {
function onTokenBridged(
address token,
uint256 value,
bytes calldata data
) external;
}
// File: contracts/libraries/TokenReader.sol
pragma solidity 0.7.5;
// solhint-disable
interface ITokenDetails {
function name() external view;
function NAME() external view;
function symbol() external view;
function SYMBOL() external view;
function decimals() external view;
function DECIMALS() external view;
}
// solhint-enable
/**
* @title TokenReader
* @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts.
*/
library TokenReader {
/**
* @dev Reads the name property of the provided token.
* Either name() or NAME() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token name as a string or an empty string if none of the methods succeeded.
*/
function readName(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.name.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.NAME.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
/**
* @dev Reads the symbol property of the provided token.
* Either symbol() or SYMBOL() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token symbol as a string or an empty string if none of the methods succeeded.
*/
function readSymbol(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.symbol.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.SYMBOL.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
/**
* @dev Reads the decimals property of the provided token.
* Either decimals() or DECIMALS() method is used.
* @param _token address of the token contract.
* @return token decimals or 0 if none of the methods succeeded.
*/
function readDecimals(address _token) internal view returns (uint8) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.decimals.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.DECIMALS.selector));
if (!status) {
return 0;
}
}
return abi.decode(data, (uint8));
}
/**
* @dev Internal function for converting returned value of name()/symbol() from bytes32/string to string.
* @param returnData data returned by the token contract.
* @return string with value obtained from returnData.
*/
function _convertToString(bytes memory returnData) private pure returns (string memory) {
if (returnData.length > 32) {
return abi.decode(returnData, (string));
} else if (returnData.length == 32) {
bytes32 data = abi.decode(returnData, (bytes32));
string memory res = new string(32);
assembly {
let len := 0
mstore(add(res, 32), data) // save value in result string
// solhint-disable
for { } gt(data, 0) { len := add(len, 1) } { // until string is empty
data := shl(8, data) // shift left by one symbol
}
// solhint-enable
mstore(res, len) // save result string length
}
return res;
} else {
return "";
}
}
}
// File: contracts/libraries/SafeMint.sol
pragma solidity 0.7.5;
/**
* @title SafeMint
* @dev Wrapper around the mint() function in all mintable tokens that verifies the return value.
*/
library SafeMint {
/**
* @dev Wrapper around IBurnableMintableERC677Token.mint() that verifies that output value is true.
* @param _token token contract.
* @param _to address of the tokens receiver.
* @param _value amount of tokens to mint.
*/
function safeMint(
IBurnableMintableERC677Token _token,
address _to,
uint256 _value
) internal {
require(_token.mint(_to, _value));
}
}
// File: contracts/upgradeable_contracts/BasicOmnibridge.sol
pragma solidity 0.7.5;
/**
* @title BasicOmnibridge
* @dev Common functionality for multi-token mediator intended to work on top of AMB bridge.
*/
abstract contract BasicOmnibridge is
Initializable,
Upgradeable,
Claimable,
OmnibridgeInfo,
TokensRelayer,
FailedMessagesProcessor,
BridgedTokensRegistry,
NativeTokensRegistry,
MediatorBalanceStorage,
TokenFactoryConnector,
TokensBridgeLimits
{
using SafeERC20 for IERC677;
using SafeMint for IBurnableMintableERC677Token;
using SafeMath for uint256;
// Workaround for storing variable up-to-32 bytes suffix
uint256 private immutable SUFFIX_SIZE;
bytes32 private immutable SUFFIX;
// Since contract is intended to be deployed under EternalStorageProxy, only constant and immutable variables can be set here
constructor(string memory _suffix) {
require(bytes(_suffix).length <= 32);
bytes32 suffix;
assembly {
suffix := mload(add(_suffix, 32))
}
SUFFIX = suffix;
SUFFIX_SIZE = bytes(_suffix).length;
}
/**
* @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
* Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function deployAndHandleBridgedTokens(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
}
/**
* @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
* Executes a callback on the receiver.
* Checks that the value is inside the execution limits and invokes the Mint accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional data passed from the other chain.
*/
function deployAndHandleBridgedTokensAndCall(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value,
bytes calldata _data
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
_receiverCallback(_recipient, bridgedToken, _value, _data);
}
/**
* @dev Handles the bridged tokens for the already registered token pair.
* Checks that the value is inside the execution limits and invokes the Mint accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleBridgedTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
}
/**
* @dev Handles the bridged tokens for the already registered token pair.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* Executes a callback on the receiver.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional transfer data passed from the other side.
*/
function handleBridgedTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
_receiverCallback(_recipient, token, _value, _data);
}
/**
* @dev Handles the bridged tokens that are native to this chain.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* @param _token native ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleNativeTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
}
/**
* @dev Handles the bridged tokens that are native to this chain.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* Executes a callback on the receiver.
* @param _token native ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional transfer data passed from the other side.
*/
function handleNativeTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
_receiverCallback(_recipient, _token, _value, _data);
}
/**
* @dev Checks if a given token is a bridged token that is native to this side of the bridge.
* @param _token address of token contract.
* @return message id of the send message.
*/
function isRegisteredAsNativeToken(address _token) public view returns (bool) {
return isTokenRegistered(_token) && nativeTokenAddress(_token) == address(0);
}
/**
* @dev Unlock back the amount of tokens that were bridged to the other network but failed.
* @param _token address that bridged token contract.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal override {
_releaseTokens(nativeTokenAddress(_token) == address(0), _token, _recipient, _value, _value);
}
/**
* @dev Allows to pre-set the bridged token contract for not-yet bridged token.
* Only the owner can call this method.
* @param _nativeToken address of the token contract on the other side that was not yet bridged.
* @param _bridgedToken address of the bridged token contract.
*/
function setCustomTokenAddressPair(address _nativeToken, address _bridgedToken) external onlyOwner {
require(!isTokenRegistered(_bridgedToken));
require(nativeTokenAddress(_bridgedToken) == address(0));
require(bridgedTokenAddress(_nativeToken) == address(0));
// Unfortunately, there is no simple way to verify that the _nativeToken address
// does not belong to the bridged token on the other side,
// since information about bridged tokens addresses is not transferred back.
// Therefore, owner account calling this function SHOULD manually verify on the other side of the bridge that
// nativeTokenAddress(_nativeToken) == address(0) && isTokenRegistered(_nativeToken) == false.
IBurnableMintableERC677Token(_bridgedToken).safeMint(address(this), 1);
IBurnableMintableERC677Token(_bridgedToken).burn(1);
_setTokenAddressPair(_nativeToken, _bridgedToken);
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer)
* @param _token address of the token contract.
* Before calling this method, it must be carefully investigated how imbalance happened
* in order to avoid an attempt to steal the funds from a token with double addresses
* (e.g. TUSD is accessible at both 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E and 0x0000000000085d4780B73119b644AE5ecd22b376)
* @param _receiver the address that will receive the tokens on the other network.
*/
function fixMediatorBalance(address _token, address _receiver)
external
onlyIfUpgradeabilityOwner
validAddress(_receiver)
{
require(isRegisteredAsNativeToken(_token));
uint256 balance = IERC677(_token).balanceOf(address(this));
uint256 expectedBalance = mediatorBalance(_token);
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx(_token);
require(available > 0);
if (diff > available) {
diff = available;
}
addTotalSpentPerDay(_token, getCurrentDay(), diff);
bytes memory data = _prepareMessage(address(0), _token, _receiver, diff, new bytes(0));
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _receiver, diff);
}
/**
* @dev Claims stuck tokens. Only unsupported tokens can be claimed.
* When dealing with already supported tokens, fixMediatorBalance can be used instead.
* @param _token address of claimed token, address(0) for native
* @param _to address of tokens receiver
*/
function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner {
// Only unregistered tokens and native coins are allowed to be claimed with the use of this function
require(_token == address(0) || !isTokenRegistered(_token));
claimValues(_token, _to);
}
/**
* @dev Withdraws erc20 tokens or native coins from the bridged token contract.
* Only the proxy owner is allowed to call this method.
* @param _bridgedToken address of the bridged token contract.
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimTokensFromTokenContract(
address _bridgedToken,
address _token,
address _to
) external onlyIfUpgradeabilityOwner {
IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to);
}
/**
* @dev Internal function for recording bridge operation for further usage.
* Recorded information is used for fixing failed requests on the other side.
* @param _messageId id of the sent message.
* @param _token bridged token address.
* @param _sender address of the tokens sender.
* @param _value bridged value.
*/
function _recordBridgeOperation(
bytes32 _messageId,
address _token,
address _sender,
uint256 _value
) internal {
setMessageToken(_messageId, _token);
setMessageRecipient(_messageId, _sender);
setMessageValue(_messageId, _value);
emit TokensBridgingInitiated(_token, _sender, _value, _messageId);
}
/**
* @dev Constructs the message to be sent to the other side. Burns/locks bridged amount of tokens.
* @param _nativeToken address of the native token contract.
* @param _token bridged token address.
* @param _receiver address of the tokens receiver on the other side.
* @param _value bridged value.
* @param _data additional transfer data passed from the other side.
*/
function _prepareMessage(
address _nativeToken,
address _token,
address _receiver,
uint256 _value,
bytes memory _data
) internal returns (bytes memory) {
bool withData = _data.length > 0 || msg.sig == this.relayTokensAndCall.selector;
// process token is native with respect to this side of the bridge
if (_nativeToken == address(0)) {
_setMediatorBalance(_token, mediatorBalance(_token).add(_value));
// process token which bridged alternative was already ACKed to be deployed
if (isBridgedTokenDeployAcknowledged(_token)) {
return
withData
? abi.encodeWithSelector(
this.handleBridgedTokensAndCall.selector,
_token,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, _value);
}
uint8 decimals = TokenReader.readDecimals(_token);
string memory name = TokenReader.readName(_token);
string memory symbol = TokenReader.readSymbol(_token);
require(bytes(name).length > 0 || bytes(symbol).length > 0);
return
withData
? abi.encodeWithSelector(
this.deployAndHandleBridgedTokensAndCall.selector,
_token,
name,
symbol,
decimals,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(
this.deployAndHandleBridgedTokens.selector,
_token,
name,
symbol,
decimals,
_receiver,
_value
);
}
// process already known token that is bridged from other chain
IBurnableMintableERC677Token(_token).burn(_value);
return
withData
? abi.encodeWithSelector(
this.handleNativeTokensAndCall.selector,
_nativeToken,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleNativeTokens.selector, _nativeToken, _receiver, _value);
}
/**
* @dev Internal function for getting minter proxy address.
* @param _token address of the token to mint.
* @return address of the minter contract that should be used for calling mint(address,uint256)
*/
function _getMinterFor(address _token) internal pure virtual returns (IBurnableMintableERC677Token) {
return IBurnableMintableERC677Token(_token);
}
/**
* Internal function for unlocking some amount of tokens.
* @param _isNative true, if token is native w.r.t. to this side of the bridge.
* @param _token address of the token contract.
* @param _recipient address of the tokens receiver.
* @param _value amount of tokens to unlock.
* @param _balanceChange amount of balance to subtract from the mediator balance.
*/
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal virtual {
if (_isNative) {
IERC677(_token).safeTransfer(_recipient, _value);
_setMediatorBalance(_token, mediatorBalance(_token).sub(_balanceChange));
} else {
_getMinterFor(_token).safeMint(_recipient, _value);
}
}
/**
* Internal function for getting address of the bridged token. Deploys new token if necessary.
* @param _token address of the token contract on the other side of the bridge.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
*/
function _getBridgedTokenOrDeploy(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals
) internal returns (address) {
address bridgedToken = bridgedTokenAddress(_token);
if (bridgedToken == address(0)) {
string memory name = _name;
string memory symbol = _symbol;
require(bytes(name).length > 0 || bytes(symbol).length > 0);
if (bytes(name).length == 0) {
name = symbol;
} else if (bytes(symbol).length == 0) {
symbol = name;
}
name = _transformName(name);
bridgedToken = tokenFactory().deploy(name, symbol, _decimals, bridgeContract().sourceChainId());
_setTokenAddressPair(_token, bridgedToken);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
} else if (!isTokenRegistered(bridgedToken)) {
require(IERC20Metadata(bridgedToken).decimals() == _decimals);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
}
return bridgedToken;
}
/**
* Notifies receiving contract about the completed bridging operation.
* @param _recipient address of the tokens receiver.
* @param _token address of the bridged token.
* @param _value amount of tokens transferred.
* @param _data additional data passed to the callback.
*/
function _receiverCallback(
address _recipient,
address _token,
uint256 _value,
bytes memory _data
) internal {
if (Address.isContract(_recipient)) {
_recipient.call(abi.encodeWithSelector(IERC20Receiver.onTokenBridged.selector, _token, _value, _data));
}
}
/**
* @dev Internal function for transforming the bridged token name. Appends a side-specific suffix.
* @param _name bridged token from the other side.
* @return token name for this side of the bridge.
*/
function _transformName(string memory _name) internal view returns (string memory) {
string memory result = string(abi.encodePacked(_name, SUFFIX));
uint256 size = SUFFIX_SIZE;
assembly {
mstore(result, add(mload(_name), size))
}
return result;
}
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal virtual;
}
// File: contracts/upgradeable_contracts/components/common/GasLimitManager.sol
pragma solidity 0.7.5;
/**
* @title GasLimitManager
* @dev Functionality for determining the request gas limit for AMB execution.
*/
abstract contract GasLimitManager is BasicAMBMediator {
bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit"))
/**
* @dev Sets the default gas limit to be used in the message execution by the AMB bridge on the other network.
* This value can't exceed the parameter maxGasPerTx defined on the AMB bridge.
* Only the owner can call this method.
* @param _gasLimit the gas limit for the message execution.
*/
function setRequestGasLimit(uint256 _gasLimit) external onlyOwner {
_setRequestGasLimit(_gasLimit);
}
/**
* @dev Tells the default gas limit to be used in the message execution by the AMB bridge on the other network.
* @return the gas limit for the message execution.
*/
function requestGasLimit() public view returns (uint256) {
return uintStorage[REQUEST_GAS_LIMIT];
}
/**
* @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network.
* @param _gasLimit the gas limit for the message execution.
*/
function _setRequestGasLimit(uint256 _gasLimit) internal {
require(_gasLimit <= maxGasPerTx());
uintStorage[REQUEST_GAS_LIMIT] = _gasLimit;
}
}
// File: contracts/upgradeable_contracts/ForeignOmnibridge.sol
pragma solidity 0.7.5;
/**
* @title ForeignOmnibridge
* @dev Foreign side implementation for multi-token mediator intended to work on top of AMB bridge.
* It is designed to be used as an implementation contract of EternalStorageProxy contract.
*/
contract ForeignOmnibridge is BasicOmnibridge, GasLimitManager {
using SafeERC20 for IERC677;
using SafeMint for IBurnableMintableERC677Token;
using SafeMath for uint256;
constructor(string memory _suffix) BasicOmnibridge(_suffix) {}
/**
* @dev Stores the initial parameters of the mediator.
* @param _bridgeContract the address of the AMB bridge contract.
* @param _mediatorContract the address of the mediator contract on the other network.
* @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network.
* [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]
* @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network.
* [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]
* @param _requestGasLimit the gas limit for the message execution.
* @param _owner address of the owner of the mediator contract.
* @param _tokenFactory address of the TokenFactory contract that will be used for the deployment of new tokens.
*/
function initialize(
address _bridgeContract,
address _mediatorContract,
uint256[3] calldata _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
uint256[2] calldata _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
uint256 _requestGasLimit,
address _owner,
address _tokenFactory
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
_setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setOwner(_owner);
_setTokenFactory(_tokenFactory);
setInitialize();
return isInitialized();
}
/**
* One-time function to be used together with upgradeToAndCall method.
* Sets the token factory contract.
* @param _tokenFactory address of the deployed TokenFactory contract.
*/
function upgradeToReverseMode(address _tokenFactory) external {
require(msg.sender == address(this));
_setTokenFactory(_tokenFactory);
}
/**
* @dev Handles the bridged tokens.
* Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly.
* @param _token token contract address on this side of the bridge.
* @param _isNative true, if given token is native to this chain and Unlock should be used.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal override {
// prohibit withdrawal of tokens during other bridge operations (e.g. relayTokens)
// such reentrant withdrawal can lead to an incorrect balanceDiff calculation
require(!lock());
require(withinExecutionLimit(_token, _value));
addTotalExecutedPerDay(_token, getCurrentDay(), _value);
_releaseTokens(_isNative, _token, _recipient, _value, _value);
emit TokensBridged(_token, _recipient, _value, messageId());
}
/**
* @dev Executes action on deposit of bridged tokens
* @param _token address of the token contract
* @param _from address of tokens sender
* @param _receiver address of tokens receiver on the other side
* @param _value requested amount of bridged tokens
* @param _data additional transfer data to be used on the other side
*/
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual override {
require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide());
// native unbridged token
if (!isTokenRegistered(_token)) {
uint8 decimals = TokenReader.readDecimals(_token);
_initializeTokenBridgeLimits(_token, decimals);
}
require(withinLimit(_token, _value));
addTotalSpentPerDay(_token, getCurrentDay(), _value);
bytes memory data = _prepareMessage(nativeTokenAddress(_token), _token, _receiver, _value, _data);
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _from, _value);
}
/**
* Internal function for unlocking some amount of tokens.
* @param _isNative true, if token is native w.r.t. to this side of the bridge.
* @param _token address of the token contract.
* @param _recipient address of the tokens receiver.
* @param _value amount of tokens to unlock.
* @param _balanceChange amount of balance to subtract from the mediator balance.
*/
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal override {
if (_isNative) {
uint256 balance = mediatorBalance(_token);
// if (_token == address(0x0Ae055097C6d159879521C384F1D2123D1f195e6) && balance < _value) {
// IBurnableMintableERC677Token(_token).safeMint(address(this), _value - balance);
// balance = _value;
// }
_setMediatorBalance(_token, balance.sub(_balanceChange));
IERC677(_token).safeTransfer(_recipient, _value);
} else {
_getMinterFor(_token).safeMint(_recipient, _value);
}
}
/**
* @dev Internal function for sending an AMB message to the mediator on the other side.
* @param _data data to be sent to the other side of the bridge.
* @param _useOracleLane always true, not used on this side of the bridge.
* @return id of the sent message.
*/
function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) {
(_useOracleLane);
return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, requestGasLimit());
}
} | * @title TokenFactory @dev Factory contract for deployment of new TokenProxy contracts./ | contract TokenFactory is OwnableModule {
address public tokenImage;
constructor(address _owner, address _tokenImage) OwnableModule(_owner) {
tokenImage = _tokenImage;
}
function setTokenImage(address _tokenImage) external onlyOwner {
require(Address.isContract(_tokenImage));
tokenImage = _tokenImage;
}
function deploy(
string calldata _name,
string calldata _symbol,
uint8 _decimals,
uint256 _chainId
) external returns (address) {
return address(new TokenProxy(tokenImage, _name, _symbol, _decimals, _chainId, msg.sender));
}
}
| 2,001,579 | [
1,
1345,
1733,
225,
7822,
6835,
364,
6314,
434,
394,
3155,
3886,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3155,
1733,
353,
14223,
6914,
3120,
288,
203,
565,
1758,
1071,
1147,
2040,
31,
203,
203,
203,
565,
3885,
12,
2867,
389,
8443,
16,
1758,
389,
2316,
2040,
13,
14223,
6914,
3120,
24899,
8443,
13,
288,
203,
3639,
1147,
2040,
273,
389,
2316,
2040,
31,
203,
565,
289,
203,
203,
565,
445,
22629,
2040,
12,
2867,
389,
2316,
2040,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
1887,
18,
291,
8924,
24899,
2316,
2040,
10019,
203,
3639,
1147,
2040,
273,
389,
2316,
2040,
31,
203,
565,
289,
203,
203,
565,
445,
7286,
12,
203,
3639,
533,
745,
892,
389,
529,
16,
203,
3639,
533,
745,
892,
389,
7175,
16,
203,
3639,
2254,
28,
389,
31734,
16,
203,
3639,
2254,
5034,
389,
5639,
548,
203,
565,
262,
3903,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1758,
12,
2704,
3155,
3886,
12,
2316,
2040,
16,
389,
529,
16,
389,
7175,
16,
389,
31734,
16,
389,
5639,
548,
16,
1234,
18,
15330,
10019,
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
] |
./full_match/80001/0xa114Ef31a6A1F66b3129A175980aCD697D3257aa/sources/@chainlink/contracts/src/v0.8/functions/dev/v1_0_0/libraries/FunctionsRequest.sol | @notice Sets bytes args for the user run function @param self The initialized request @param args The array of bytes args (must not be empty) | function setBytesArgs(Request memory self, bytes[] memory args) internal pure {
if (args.length == 0) revert EmptyArgs();
self.bytesArgs = args;
}
| 5,585,515 | [
1,
2785,
1731,
833,
364,
326,
729,
1086,
445,
225,
365,
1021,
6454,
590,
225,
833,
1021,
526,
434,
1731,
833,
261,
11926,
486,
506,
1008,
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
] | [
1,
1,
1,
1,
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,
225,
445,
444,
2160,
2615,
12,
691,
3778,
365,
16,
1731,
8526,
3778,
833,
13,
2713,
16618,
288,
203,
565,
309,
261,
1968,
18,
2469,
422,
374,
13,
15226,
8953,
2615,
5621,
203,
203,
565,
365,
18,
3890,
2615,
273,
833,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
import "./OpenZeppelin/Ownable.sol";
import "./BerryToken.sol";
/*
* ICO Start time - 1512464400 - December 5, 2018 9:00:00 AM
* Default ICO End time - 1519862399 - February 28, 2018 11:59:59 PM
*/
contract BerryCrowdsale is Ownable {
using SafeMath for uint;
BerryToken public token = new BerryToken();
uint totalSupply = token.totalSupply();
bool public isRefundAllowed;
bool public newBonus_and_newPeriod;
bool public new_bonus_for_next_period;
uint public icoStartTime;
uint public icoEndTime;
uint public weiRaised;
uint public hardCap; // amount of ETH collected, which marks end of crowd sale
uint public tokensDistributed; // amount of bought tokens
uint public bonus_for_add_stage;
/* Bonus variables */
uint internal baseBonus1 = 127;
uint internal baseBonus2 = 120;
uint internal baseBonus3 = 113;
uint internal baseBonus4 = 107;
uint internal baseBonus5 = 100;
uint public manualBonus;
/* * * * * * * * * * * * * * * * * * */
uint public rate; // how many token units a buyer gets per wei
uint private icoMinPurchase; // In ETH
uint private icoEndDateIncCount;
address[] public investors_number;
address private wallet; // address where funds are collected
mapping (address => uint) public orderedTokens;
mapping (address => uint) contributors;
event FundsWithdrawn(address _who, uint256 _amount);
modifier hardCapNotReached() {
require(weiRaised < hardCap);
_;
}
modifier crowdsaleEnded() {
require(now > icoEndTime);
_;
}
modifier crowdsaleInProgress() {
bool withinPeriod = (now >= icoStartTime && now <= icoEndTime);
require(withinPeriod);
_;
}
function BerryCrowdsale(uint _icoStartTime, uint _icoEndTime, address _wallet) public {
require (
_icoStartTime > now &&
_icoEndTime > _icoStartTime
);
icoStartTime = _icoStartTime;
icoEndTime = _icoEndTime;
wallet = _wallet;
rate = 4E14; // wei per 1 token
hardCap = 100000 ether;
icoEndDateIncCount = 0;
icoMinPurchase = 100 finney; // 0.1 ETH
isRefundAllowed = false;
}
// fallback function can be used to buy tokens
function() public payable {
buyTokens();
}
// low level token purchase function
function buyTokens() public payable crowdsaleInProgress hardCapNotReached {
require(msg.value > 0);
// check if the buyer exceeded the funding goal
calculatePurchaseAndBonuses(msg.sender, msg.value);
}
// Returns number of investors
function getInvestorCount() public view returns (uint) {
return investors_number.length;
}
// Owner can allow or disallow refunds even if soft cap is reached. Should be used in case KYC is not passed.
// WARNING: owner should transfer collected ETH back to contract before allowing to refund, if he already withdrawn ETH.
function toggleRefunds() public onlyOwner {
isRefundAllowed = true;
}
// Sends ordered tokens to investors after ICO end if soft cap is reached
// tokens can be send only if ico has ended
function sendOrderedTokens() public onlyOwner crowdsaleEnded {
address investor;
uint tokensCount;
for(uint i = 0; i < investors_number.length; i++) {
investor = investors_number[i];
tokensCount = orderedTokens[investor];
assert(tokensCount > 0);
orderedTokens[investor] = 0;
token.transfer(investor, tokensCount);
}
}
// Moves ICO ending date by one month. End date can be moved only 3 times.
// Returns true if ICO end date was successfully shifted
function moveIcoEndDateByOneMonth(uint bonus_percentage) public onlyOwner crowdsaleInProgress returns (bool) {
if (icoEndDateIncCount < 3) {
icoEndTime = icoEndTime.add(30 days);
icoEndDateIncCount++;
newBonus_and_newPeriod = true;
bonus_for_add_stage = bonus_percentage;
return true;
}
else {
return false;
}
}
// Owner can send back collected ETH if soft cap is not reached or KYC is not passed
// WARNING: crowdsale contract should have all received funds to return them.
// If you have already withdrawn them, send them back to crowdsale contract
function refundInvestors() public onlyOwner {
require(now >= icoEndTime);
require(isRefundAllowed);
require(msg.sender.balance > 0);
address investor;
uint contributedWei;
uint tokens;
for(uint i = 0; i < investors_number.length; i++) {
investor = investors_number[i];
contributedWei = contributors[investor];
tokens = orderedTokens[investor];
if(contributedWei > 0) {
weiRaised = weiRaised.sub(contributedWei);
contributors[investor] = 0;
orderedTokens[investor] = 0;
tokensDistributed = tokensDistributed.sub(tokens);
investor.transfer(contributedWei); // return funds back to contributor
}
}
}
// Owner of contract can withdraw collected ETH, if soft cap is reached, by calling this function
function withdraw() public onlyOwner {
uint to_send = weiRaised;
weiRaised = 0;
FundsWithdrawn(msg.sender, to_send);
wallet.transfer(to_send);
}
// This function should be used to manually reserve some tokens for "big sharks" or bug-bounty program participants
function manualReserve(address _beneficiary, uint _amount) public onlyOwner crowdsaleInProgress {
require(_beneficiary != address(0));
require(_amount > 0);
checkAndMint(_amount);
tokensDistributed = tokensDistributed.add(_amount);
token.transfer(_beneficiary, _amount);
}
function burnUnsold() public onlyOwner crowdsaleEnded {
uint tokensLeft = totalSupply.sub(tokensDistributed);
token.burn(tokensLeft);
}
function finishIco() public onlyOwner {
icoEndTime = now;
}
function distribute_for_founders() public crowdsaleEnded onlyOwner {
uint to_send = totalSupply.mul(30).div(70);
checkAndMint(to_send);
token.transfer(wallet, to_send);
}
function transferOwnershipToken(address _to) public onlyOwner {
token.transferOwnership(_to);
}
/***************************
** Internal functions **
***************************/
// Calculates purchase conditions and token bonuses
function calculatePurchaseAndBonuses(address _beneficiary, uint _weiAmount) internal {
if (now >= icoStartTime && now < icoEndTime) require(_weiAmount >= icoMinPurchase);
uint cleanWei; // amount of wei to use for purchase excluding change and hardcap overflows
uint change;
uint _tokens;
//check for hardcap overflow
if (_weiAmount.add(weiRaised) > hardCap) {
cleanWei = hardCap.sub(weiRaised);
change = _weiAmount.sub(cleanWei);
}
else cleanWei = _weiAmount;
assert(cleanWei > 4); // 4 wei is a price of minimal fracture of token
_tokens = cleanWei.mul(rate).mul(2500).div(1 ether);
if (contributors[_beneficiary] == 0) investors_number.push(_beneficiary);
_tokens = calculateBonus(_tokens, cleanWei);
checkAndMint(_tokens);
contributors[_beneficiary] = contributors[_beneficiary].add(cleanWei);
weiRaised = weiRaised.add(cleanWei);
tokensDistributed = tokensDistributed.add(_tokens);
orderedTokens[_beneficiary] = orderedTokens[_beneficiary].add(_tokens);
if (change > 0) _beneficiary.transfer(change);
}
// Calculates bonuses based on current stage
function calculateBonus(uint _baseAmount, uint _wei) internal returns (uint) {
require(_baseAmount > 0 && _wei > 0);
if (now >= icoStartTime && now < icoEndTime) {
return calculateBonusIco(_baseAmount, _wei);
}
else return _baseAmount;
}
function setBonusForNextStage (uint newBonusPercentage) public onlyOwner {
manualBonus = newBonusPercentage.add(100);
new_bonus_for_next_period = true;
}
function check_for_manual_bonus (uint _baseBonus) internal returns (uint) {
if (new_bonus_for_next_period) {
new_bonus_for_next_period = false;
return manualBonus;
} else
return _baseBonus;
}
// Calculates bonuses, specific for the ICO
// Contains date and volume based bonuses
function calculateBonusIco(uint _baseAmount, uint _wei) internal returns(uint) {
if(now >= icoStartTime && now < 1513727999) {
// 5-19 Dec - 33% bonus
return _baseAmount.mul(133).div(100);
}
else if(now >= 1513728000 && now < 1514332799) {
// 20-26 - 27% bonus
baseBonus1 = check_for_manual_bonus(baseBonus1); // returns 127 if no changes detected
return _baseAmount.mul(baseBonus1).div(100);
}
else if(now >= 1514332800 && now < 1516147199) {
// 27 dec - 16 jan - 20% bonus
baseBonus2 = check_for_manual_bonus(baseBonus2);
return _baseAmount.mul(baseBonus2).div(100);
}
else if(now >= 1516147200 && now < 1517356799) {
// 17-30 jan - 13% bonus
baseBonus3 = check_for_manual_bonus(baseBonus3);
return _baseAmount.mul(baseBonus3).div(100);
}
else if(now >= 1517356800 && now < 1518566399) {
//31 jan - 13 feb 7 % bonus
baseBonus4 = check_for_manual_bonus(baseBonus4);
return _baseAmount.mul(baseBonus4).div(100);
}
else if(now >= 1518566400 && now < 1519862399) {
//14-28 feb - no bonus
baseBonus5 = check_for_manual_bonus(baseBonus5);
return _baseAmount.mul(baseBonus5).div(100);
}
else if (newBonus_and_newPeriod) {
return _baseAmount.mul(bonus_for_add_stage.add(100)).div(100);
}
else if(now < icoEndTime) {
if(_wei >= 1 ether && _wei < 3 ether) {
return _baseAmount.mul(101).div(100);
}
else if(_wei >= 3 ether && _wei < 5 ether) {
return _baseAmount.mul(102).div(100);
}
else if(_wei >= 5 ether) {
return _baseAmount.mul(103).div(100);
}
else {
return _baseAmount;
}
}
}
// Checks if more tokens should be minted based on amount of sold tokens, required additional tokens and total supply.
// If there are not enough tokens, mint missing tokens
function checkAndMint(uint _amount) internal {
uint required = tokensDistributed.add(_amount);
if(required > totalSupply) token.mint(this, required.sub(totalSupply));
}
}
| Returns number of investors | function getInvestorCount() public view returns (uint) {
return investors_number.length;
}
| 990,178 | [
1,
1356,
1300,
434,
2198,
395,
1383,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
3605,
395,
280,
1380,
1435,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
2198,
395,
1383,
67,
2696,
18,
2469,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-01
*/
// 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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
/**
* @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);
}
}
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @dev 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());
}
}
interface InterfacePunkAsses {
function punkassBalance(address owner) external view returns(uint256);
}
contract Ass is ERC20, Ownable, Pausable {
InterfacePunkAsses public PunkAsses;
// The starting block.
uint256 public startBlock;
// The interval that the user is paid out.
uint256 public interval = 86400;
uint256 public rate = 4 ether;
address public ticketContract;
// The rewards for the user.
mapping(address => uint256) public rewards;
// The last time they were paid out.
mapping(address => uint256) public lastUpdate;
// Only allow the contract to interact with it.
modifier onlyFromPunkAsses() {
require(msg.sender == address(PunkAsses));
_;
}
constructor(address punkAssesAddress) ERC20("Ass", "Ass") {
// Set who the evofoxes address.
PunkAsses = InterfacePunkAsses(punkAssesAddress);
// Set the starting block.
startBlock = block.timestamp;
// Set to the owner for now.
ticketContract = msg.sender;
// Pause the system so no one can interact with it.
_pause();
}
// Pause it.
function pause() public onlyOwner { _pause(); }
// Unpause it.
function unpause() public onlyOwner { _unpause(); }
// Set the start block.
function setStartBlock(uint256 arg) public onlyOwner {
if(arg == 0){
startBlock = block.timestamp;
}else{
startBlock = arg;
}
}
// Set the start block.
function setIntervalAndRate(uint256 _interval, uint256 _rate) public onlyOwner {
interval = _interval;
rate = _rate;
}
// Set the address for the contract.
function setPunkAssesContractAddress(address _punkAsses) public onlyOwner {
PunkAsses = InterfacePunkAsses(_punkAsses);
}
// Set the address for the contract.
function setTicketContractAddress(address _punkAsses) public onlyOwner {
ticketContract = _punkAsses;
}
// Burn the tokens required to evolve.
function burn(address user, uint256 amount) external {
require(msg.sender == address(ticketContract), "Your address does not have permission to use burn");
_burn(user, amount);
}
// Mint some tokens for uniswap.
function adminCreate(address user, uint256 amount) public onlyOwner {
_mint(user, amount);
}
// Transfer the tokens (only accessable from the contract).
function transferTokens(address _from, address _to) onlyFromPunkAsses whenNotPaused external {
// Refactor this.
if(_from != address(0)){
rewards[_from] += getPendingReward(_from);
lastUpdate[_from] = block.timestamp;
}
if(_to != address(0)){
rewards[_to] += getPendingReward(_to);
lastUpdate[_to] = block.timestamp;
}
}
// Pay out the holder.
function claimReward() external whenNotPaused {
// Mint the user their tokens.
_mint(msg.sender, rewards[msg.sender] + getPendingReward(msg.sender));
// Reset the rewards for the user.
rewards[msg.sender] = 0;
lastUpdate[msg.sender] = block.timestamp;
}
// The rewards to the user.
function getTotalClaimable(address user) external view returns(uint256) {
return rewards[user] + getPendingReward(user);
}
// The rewards to the user.
function getlastUpdate(address user) external view returns(uint256) {
return lastUpdate[user];
}
// Get the total rewards.
function getPendingReward(address user) internal view returns(uint256) {
return PunkAsses.punkassBalance(user) *
rate *
(block.timestamp - (lastUpdate[user] >= startBlock ? lastUpdate[user] : startBlock)) /
interval;
}
} | * @dev Initializes the contract setting the deployer as the initial owner./ | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
constructor() {
_setOwner(_msgSender());
}
| 15,261,506 | [
1,
9685,
326,
6835,
3637,
326,
7286,
264,
487,
326,
2172,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
203,
565,
445,
389,
5205,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
7010,
203,
203,
203,
203,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
542,
5541,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xebaa1766c577a1ea5833f0502bd9984aef22c61f
//Contract name: DadiSale
//Balance: 0 Ether
//Verification Date: 2/5/2018
//Transacion Count: 67
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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 constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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));
// 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 constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/*****
* @title A DADI Contract
*/
contract DadiSale is Ownable {
using SafeMath for uint256;
StandardToken public token; // The DADI ERC20 token */
address[] public saleWallets;
struct WhitelistUser {
uint256 pledged;
uint index;
}
struct Investor {
uint256 tokens;
uint256 contribution;
bool distributed;
uint index;
}
uint256 public tokenSupply;
uint256 public tokensPurchased = 0;
uint256 public tokenPrice = 500; // USD$0.50
uint256 public ethRate = 200; // ETH to USD Rate, set by owner: 1 ETH = ethRate USD
mapping(address => WhitelistUser) private whitelisted;
address[] private whitelistedIndex;
mapping(address => Investor) private investors;
address[] private investorIndex;
/*****
* State for Sale Modes
* 0 - Preparing: All contract initialization calls
* 1 - Sale: Contract is in the Sale Period
* 2 - SaleFinalized Sale period is finalized, no more payments are allowed
* 3 - Success: Sale Successful
* 4 - TokenDistribution: Sale finished, tokens can be distributed
* 5 - Closed: Sale closed, no tokens more can be distributed
*/
enum SaleState { Preparing, Sale, SaleFinalized, Success, TokenDistribution, Closed }
SaleState public state = SaleState.Preparing;
event LogTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens);
event LogTokenDistribution(address recipient, uint256 tokens);
event LogRedistributeTokens(address recipient, SaleState _state, uint256 tokens);
event LogFundTransfer(address wallet, uint256 value);
event LogRefund(address wallet, uint256 value);
event LogStateChange(SaleState _state);
event LogNewWhitelistUser(address indexed userAddress, uint index, uint256 value);
/*****
* @dev Modifier to check that amount transferred is not 0
*/
modifier nonZero() {
require(msg.value != 0);
_;
}
/*****
* @dev The constructor function to initialize the sale
* @param _token address the address of the ERC20 token for the sale
* @param _tokenSupply uint256 the amount of tokens available
*/
function DadiSale (StandardToken _token, uint256 _tokenSupply) public {
require(_token != address(0));
require(_tokenSupply != 0);
token = StandardToken(_token);
tokenSupply = _tokenSupply * (uint256(10) ** 18);
}
/*****
* @dev Fallback Function to buy the tokens
*/
function () public nonZero payable {
require(state == SaleState.Sale);
buyTokens(msg.sender, msg.value);
}
/*****
* @dev Allows the contract owner to add a new Sale wallet, used to hold funds safely
* @param _wallet address The address of the wallet
* @return success bool Returns true if executed successfully
*/
function addSaleWallet (address _wallet) public onlyOwner returns (bool) {
require(_wallet != address(0));
saleWallets.push(_wallet);
return true;
}
/*****
* @dev Allows the contract owner to a single whitelist user
* @param userAddress address The wallet address to whitelist
* @param pledged uint256 The amount pledged by the user
*/
function addWhitelistUser(address userAddress, uint256 pledged) public onlyOwner {
if (!isWhitelisted(userAddress)) {
whitelisted[userAddress].index = whitelistedIndex.push(userAddress) - 1;
LogNewWhitelistUser(userAddress, whitelisted[userAddress].index, pledged);
}
whitelisted[userAddress].pledged = pledged * 1000;
}
/*****
* @dev Calculates the number of tokens that can be bought for the amount of Wei transferred
* @param _amount uint256 The amount of money invested by the investor
* @return tokens uint256 The number of tokens purchased for the amount invested
*/
function calculateTokens (uint256 _amount) public constant returns (uint256 tokens) {
tokens = _amount * ethRate / tokenPrice;
return tokens;
}
/*****
* @dev Called by the owner of the contract to modify the sale state
*/
function setState (uint256 _state) public onlyOwner {
state = SaleState(uint(_state));
LogStateChange(state);
}
/*****
* @dev Called by the owner of the contract to start the Sale
* @param rate uint256 the current ETH USD rate, multiplied by 1000
*/
function startSale (uint256 rate) public onlyOwner {
state = SaleState.Sale;
updateEthRate(rate);
LogStateChange(state);
}
/*****
* @dev Allow updating the ETH USD exchange rate
* @param rate uint256 the current ETH USD rate, multiplied by 1000
* @return bool Return true if the contract is in PartnerSale Period
*/
function updateEthRate (uint256 rate) public onlyOwner returns (bool) {
require(rate >= 100000);
ethRate = rate;
return true;
}
function updateTokenSupply (uint256 _tokenSupply) public onlyOwner returns (bool) {
require(_tokenSupply != 0);
tokenSupply = _tokenSupply * (uint256(10) ** 18);
return true;
}
/*****
* @dev Allows transfer of tokens to a recipient who has purchased offline, during the Sale
* @param _recipient address The address of the recipient of the tokens
* @param _tokens uint256 The number of tokens purchased by the recipient
* @return success bool Returns true if executed successfully
*/
function offlineTransaction (address _recipient, uint256 _tokens) public onlyOwner returns (bool) {
require(_tokens > 0);
// Convert to a token with decimals
uint256 tokens = _tokens * (uint256(10) ** uint8(18));
// if the number of tokens is greater than available, reject tx
if (tokens >= getTokensAvailable()) {
revert();
}
addToInvestor(_recipient, 0, tokens);
// Increase the count of tokens purchased in the sale
updateSaleParameters(tokens);
LogTokenPurchase(msg.sender, _recipient, 0, tokens);
return true;
}
/*****
* @dev Called by the owner of the contract to finalize the ICO
* and redistribute funds (if any)
*/
function finalizeSale () public onlyOwner {
state = SaleState.Success;
LogStateChange(state);
// Transfer any ETH to one of the Sale wallets
if (this.balance > 0) {
forwardFunds(this.balance);
}
}
/*****
* @dev Called by the owner of the contract to close the Sale and redistribute any crumbs.
* @param recipient address The address of the recipient of the tokens
*/
function closeSale (address recipient) public onlyOwner {
state = SaleState.Closed;
LogStateChange(state);
// redistribute unsold tokens to DADI ecosystem
uint256 remaining = getTokensAvailable();
updateSaleParameters(remaining);
if (remaining > 0) {
token.transfer(recipient, remaining);
LogRedistributeTokens(recipient, state, remaining);
}
}
/*****
* @dev Called by the owner of the contract to allow tokens to be distributed
*/
function setTokenDistribution () public onlyOwner {
state = SaleState.TokenDistribution;
LogStateChange(state);
}
/*****
* @dev Called by the owner of the contract to distribute tokens to investors
* @param _address address The address of the investor for which to distribute tokens
* @return success bool Returns true if executed successfully
*/
function distributeTokens (address _address) public onlyOwner returns (bool) {
require(state == SaleState.TokenDistribution);
// get the tokens available for the investor
uint256 tokens = investors[_address].tokens;
require(tokens > 0);
require(investors[_address].distributed == false);
investors[_address].distributed = true;
token.transfer(_address, tokens);
LogTokenDistribution(_address, tokens);
return true;
}
/*****
* @dev Called by the owner of the contract to distribute tokens to investors who used a non-ERC20 wallet address
* @param _purchaseAddress address The address the investor used to buy tokens
* @param _tokenAddress address The address to send the tokens to
* @return success bool Returns true if executed successfully
*/
function distributeToAlternateAddress (address _purchaseAddress, address _tokenAddress) public onlyOwner returns (bool) {
require(state == SaleState.TokenDistribution);
// get the tokens available for the investor
uint256 tokens = investors[_purchaseAddress].tokens;
require(tokens > 0);
require(investors[_purchaseAddress].distributed == false);
investors[_purchaseAddress].distributed = true;
token.transfer(_tokenAddress, tokens);
LogTokenDistribution(_tokenAddress, tokens);
return true;
}
/*****
* @dev Called by the owner of the contract to redistribute tokens if an investor has been refunded offline
* @param investorAddress address The address the investor used to buy tokens
* @param recipient address The address to send the tokens to
*/
function redistributeTokens (address investorAddress, address recipient) public onlyOwner {
uint256 tokens = investors[investorAddress].tokens;
require(tokens > 0);
require(investors[investorAddress].distributed == false);
// set flag, so they can't be redistributed
investors[investorAddress].distributed = true;
token.transfer(recipient, tokens);
LogRedistributeTokens(recipient, state, tokens);
}
/*****
* @dev Get the amount of Sale tokens left for purchase
* @return uint256 the count of tokens available
*/
function getTokensAvailable () public constant returns (uint256) {
return tokenSupply - tokensPurchased;
}
/*****
* @dev Get the total count of tokens purchased in all the Sale periods
* @return uint256 the count of tokens purchased
*/
function getTokensPurchased () public constant returns (uint256) {
return tokensPurchased;
}
/*****
* @dev Get the balance sent to the contract
* @return uint256 the amount sent to this contract, in Wei
*/
function getBalance () public constant returns (uint256) {
return this.balance;
}
/*****
* @dev Converts an amount sent in Wei to the equivalent in USD
* @param _amount uint256 the amount sent to the contract, in Wei
* @return uint256 the amount sent to this contract, in USD
*/
function ethToUsd (uint256 _amount) public constant returns (uint256) {
return (_amount * ethRate) / (uint256(10) ** 18);
}
/*****
* @dev Get a whitelisted user
* @param userAddress address the wallet address of the user
* @return uint256 the amount pledged by the user
* @return uint the index of the user
*/
function getWhitelistUser (address userAddress) public constant returns (uint256 pledged, uint index) {
require(isWhitelisted(userAddress));
return(whitelisted[userAddress].pledged, whitelisted[userAddress].index);
}
/*****
* @dev Get count of contributors
* @return uint the number of unique contributors
*/
function getInvestorCount () public constant returns (uint count) {
return investorIndex.length;
}
/*****
* @dev Get an investor
* @param _address address the wallet address of the investor
* @return uint256 the amount contributed by the user
* @return uint256 the number of tokens assigned to the user
* @return uint the index of the user
*/
function getInvestor (address _address) public constant returns (uint256 contribution, uint256 tokens, bool distributed, uint index) {
require(isInvested(_address));
return(investors[_address].contribution, investors[_address].tokens, investors[_address].distributed, investors[_address].index);
}
/*****
* @dev Get a user's whitelisted state
* @param userAddress address the wallet address of the user
* @return bool true if the user is in the whitelist
*/
function isWhitelisted (address userAddress) internal constant returns (bool isIndeed) {
if (whitelistedIndex.length == 0) return false;
return (whitelistedIndex[whitelisted[userAddress].index] == userAddress);
}
/*****
* @dev Get a user's invested state
* @param _address address the wallet address of the user
* @return bool true if the user has already contributed
*/
function isInvested (address _address) internal constant returns (bool isIndeed) {
if (investorIndex.length == 0) return false;
return (investorIndex[investors[_address].index] == _address);
}
/*****
* @dev Update a user's invested state
* @param _address address the wallet address of the user
* @param _value uint256 the amount contributed in this transaction
* @param _tokens uint256 the number of tokens assigned in this transaction
*/
function addToInvestor(address _address, uint256 _value, uint256 _tokens) internal {
// add the user to the investorIndex if this is their first contribution
if (!isInvested(_address)) {
investors[_address].index = investorIndex.push(_address) - 1;
}
investors[_address].tokens = investors[_address].tokens.add(_tokens);
investors[_address].contribution = investors[_address].contribution.add(_value);
investors[_address].distributed = false;
}
/*****
* @dev Send ether to the Sale collection wallets
*/
function forwardFunds (uint256 _value) internal {
uint accountNumber;
address account;
// move funds to a random SaleWallet
if (saleWallets.length > 0) {
accountNumber = getRandom(saleWallets.length) - 1;
account = saleWallets[accountNumber];
account.transfer(_value);
LogFundTransfer(account, _value);
}
}
/*****
* @dev Internal function to assign tokens to the contributor
* @param _address address The address of the contributing investor
* @param _value uint256 The amount invested
* @return success bool Returns true if executed successfully
*/
function buyTokens (address _address, uint256 _value) internal returns (bool) {
require(isWhitelisted(_address));
require(isValidContribution(_address, _value));
uint256 boughtTokens = calculateTokens(_value);
require(boughtTokens != 0);
// if the number of tokens calculated for the given value is
// greater than the tokens available, reject the payment
if (boughtTokens > getTokensAvailable()) {
revert();
}
// update investor state
addToInvestor(_address, _value, boughtTokens);
forwardFunds(_value);
updateSaleParameters(boughtTokens);
LogTokenPurchase(msg.sender, _address, _value, boughtTokens);
return true;
}
/*****
* @dev Check that the amount sent in the transaction is below the pledged amount.
* Factors in previous transactions by the same user
* @param _address address The address of the user making the transaction
* @param _amount uint256 The amount sent in the transaction
* @return bool Returns true if the amount is valid
*/
function isValidContribution (address _address, uint256 _amount) internal constant returns (bool valid) {
return ethToUsd(_amount + investors[_address].contribution) <= whitelisted[_address].pledged;
}
/*****
* @dev Generates a random number from 1 to max based on the last block hash
* @param max uint the maximum value
* @return a random number
*/
function getRandom(uint max) internal constant returns (uint randomNumber) {
return (uint(keccak256(block.blockhash(block.number - 1))) % max) + 1;
}
/*****
* @dev Internal function to modify parameters based on tokens bought
* @param _tokens uint256 The number of tokens purchased
*/
function updateSaleParameters (uint256 _tokens) internal {
tokensPurchased = tokensPurchased.add(_tokens);
}
}
| **** @dev Converts an amount sent in Wei to the equivalent in USD @param _amount uint256 the amount sent to the contract, in Wei @return uint256 the amount sent to this contract, in USD/ | function ethToUsd (uint256 _amount) public constant returns (uint256) {
return (_amount * ethRate) / (uint256(10) ** 18);
}
| 7,307,308 | [
1,
5692,
392,
3844,
3271,
316,
1660,
77,
358,
326,
7680,
316,
587,
9903,
225,
389,
8949,
1377,
2254,
5034,
4202,
326,
3844,
3271,
358,
326,
6835,
16,
316,
1660,
77,
327,
2254,
5034,
225,
326,
3844,
3271,
358,
333,
6835,
16,
316,
587,
9903,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
13750,
774,
3477,
72,
261,
11890,
5034,
389,
8949,
13,
1071,
5381,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
261,
67,
8949,
380,
13750,
4727,
13,
342,
261,
11890,
5034,
12,
2163,
13,
2826,
6549,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.0;
/**
* @dev The Migrations contract is a standard truffle contract that keeps track of which migrations were done on the current network.
* For eDai, we have updated it and added functionality that enables it as well to work as a deployed contract registry.
*/
contract Migrations {
event Registered(bytes32 name, address addr);
uint public lastCompletedMigration;
string public version;
/// @dev Deployed contract to deployment address
mapping(bytes32 => address) public contracts;
/// @dev Contract name iterator
bytes32[] public names;
constructor (string memory version_) public {
version = version_;
}
/// @dev Amount of registered contracts
function length() public virtual view returns (uint) {
return names.length;
}
/// @dev Register a contract name and address
function register(bytes32 name, address addr ) public {
contracts[name] = addr;
names.push(name);
emit Registered(name, addr);
}
/// @dev Register the index of the last completed migration
function setCompleted(uint completed) public {
lastCompletedMigration = completed;
}
/// @dev Copy the index of the last completed migration to a new version of the Migrations contract
function upgrade(address newAddress) public {
Migrations upgraded = Migrations(newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| * @dev The Migrations contract is a standard truffle contract that keeps track of which migrations were done on the current network. For eDai, we have updated it and added functionality that enables it as well to work as a deployed contract registry./ | contract Migrations {
event Registered(bytes32 name, address addr);
uint public lastCompletedMigration;
string public version;
mapping(bytes32 => address) public contracts;
bytes32[] public names;
pragma solidity ^0.6.0;
constructor (string memory version_) public {
version = version_;
}
function length() public virtual view returns (uint) {
return names.length;
}
function register(bytes32 name, address addr ) public {
contracts[name] = addr;
names.push(name);
emit Registered(name, addr);
}
function setCompleted(uint completed) public {
lastCompletedMigration = completed;
}
function upgrade(address newAddress) public {
Migrations upgraded = Migrations(newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| 12,780,831 | [
1,
1986,
490,
10475,
6835,
353,
279,
4529,
433,
10148,
6835,
716,
20948,
3298,
434,
1492,
9814,
4591,
2731,
603,
326,
783,
2483,
18,
2457,
425,
40,
10658,
16,
732,
1240,
3526,
518,
471,
3096,
14176,
716,
19808,
518,
487,
5492,
358,
1440,
487,
279,
19357,
6835,
4023,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
490,
10475,
288,
203,
565,
871,
26940,
12,
3890,
1578,
508,
16,
1758,
3091,
1769,
203,
565,
2254,
1071,
1142,
9556,
10224,
31,
203,
565,
533,
1071,
1177,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1758,
13,
1071,
20092,
31,
203,
203,
565,
1731,
1578,
8526,
1071,
1257,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
565,
3885,
261,
1080,
3778,
1177,
67,
13,
1071,
288,
203,
3639,
1177,
273,
1177,
67,
31,
203,
565,
289,
203,
203,
565,
445,
769,
1435,
1071,
5024,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
1257,
18,
2469,
31,
203,
565,
289,
203,
203,
565,
445,
1744,
12,
3890,
1578,
508,
16,
1758,
3091,
262,
1071,
288,
203,
3639,
20092,
63,
529,
65,
273,
3091,
31,
203,
3639,
1257,
18,
6206,
12,
529,
1769,
203,
3639,
3626,
26940,
12,
529,
16,
3091,
1769,
203,
565,
289,
203,
203,
565,
445,
444,
9556,
12,
11890,
5951,
13,
1071,
288,
203,
3639,
1142,
9556,
10224,
273,
5951,
31,
203,
565,
289,
203,
203,
565,
445,
8400,
12,
2867,
394,
1887,
13,
1071,
288,
203,
3639,
490,
10475,
31049,
273,
490,
10475,
12,
2704,
1887,
1769,
203,
3639,
31049,
18,
542,
9556,
12,
2722,
9556,
10224,
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
] |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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");
}
}
/**
* @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");
}
}
}
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;
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Decimal
* @notice Library that defines a fixed-point number with 18 decimal places.
*
* audit-info: Extended from dYdX's Decimal library:
* https://github.com/dydxprotocol/solo/blob/master/contracts/protocol/lib/Decimal.sol
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
/**
* @notice Fixed-point base for Decimal.D256 values
*/
uint256 constant BASE = 10**18;
// ============ Structs ============
/**
* @notice Main struct to hold Decimal.D256 state
* @dev Represents the number value / BASE
*/
struct D256 {
/**
* @notice Underlying value of the Decimal.D256
*/
uint256 value;
}
// ============ Static Functions ============
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 0.0
* @return Decimal.D256 representation of 0.0
*/
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 1.0
* @return Decimal.D256 representation of 1.0
*/
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a`
* @param a Integer to transform to Decimal.D256 type
* @return Decimal.D256 representation of integer`a`
*/
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a` / `b`
* @param a Numerator of ratio to transform to Decimal.D256 type
* @param b Denominator of ratio to transform to Decimal.D256 type
* @return Decimal.D256 representation of ratio `a` / `b`
*/
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
/**
* @notice Adds integer `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
uint256 amount = b.mul(BASE);
return D256({ value: self.value > amount ? self.value.sub(amount) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b, reason) });
}
/**
* @notice Exponentiates Decimal.D256 `self` to the power of integer `b`
* @dev Not optimized - is only suitable to use with small exponents
* @param self Original Decimal.D256 number
* @param b Integer exponent
* @return Resulting Decimal.D256
*/
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
/**
* @notice Adds Decimal.D256 `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value > b.value ? self.value.sub(b.value) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value, reason) });
}
/**
* @notice Checks if `b` is equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is equal to `self`
*/
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
/**
* @notice Checks if `b` is greater than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than `self`
*/
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
/**
* @notice Checks if `b` is less than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than `self`
*/
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
/**
* @notice Checks if `b` is greater than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than or equal to `self`
*/
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
/**
* @notice Checks if `b` is less than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than or equal to `self`
*/
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
/**
* @notice Checks if `self` is equal to 0
* @param self Original Decimal.D256 number
* @return Whether `self` is equal to 0
*/
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
/**
* @notice Truncates the decimal part of `self` and returns the integer value as a uint256
* @param self Original Decimal.D256 number
* @return Truncated Integer value as a uint256
*/
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ General Math ============
/**
* @notice Determines the minimum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting minimum Decimal.D256
*/
function min(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return lessThan(a, b) ? a : b;
}
/**
* @notice Determines the maximum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting maximum Decimal.D256
*/
function max(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return greaterThan(a, b) ? a : b;
}
// ============ Core Methods ============
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* Reverts on divide-by-zero with reason `reason`
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @param reason Revert reason
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator,
string memory reason
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator, reason);
}
/**
* @notice Compares Decimal.D256 `a` to Decimal.D256 `b`
* @dev Internal only - helper
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return 0 if a < b, 1 if a == b, 2 if a > b
*/
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
Copyright 2020, 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title IManagedToken
* @notice Generic interface for ERC20 tokens that can be minted and burned by their owner
* @dev Used by Dollar and Stake in this protocol
*/
interface IManagedToken {
/**
* @notice Mints `amount` tokens to the {owner}
* @param amount Amount of token to mint
*/
function burn(uint256 amount) external;
/**
* @notice Burns `amount` tokens from the {owner}
* @param amount Amount of token to burn
*/
function mint(uint256 amount) external;
}
/**
* @title IGovToken
* @notice Generic interface for ERC20 tokens that have Compound-governance features
* @dev Used by Stake and other compatible reserve-held tokens
*/
interface IGovToken {
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external;
}
/**
* @title IReserve
* @notice Interface for the protocol reserve
*/
interface IReserve {
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* @return Current ESD redemption price
*/
function redeemPrice() external view returns (Decimal.D256 memory);
}
interface IRegistry {
/**
* @notice USDC token contract
*/
function usdc() external view returns (address);
/**
* @notice Compound protocol cUSDC pool
*/
function cUsdc() external view returns (address);
/**
* @notice ESD stablecoin contract
*/
function dollar() external view returns (address);
/**
* @notice ESDS governance token contract
*/
function stake() external view returns (address);
/**
* @notice ESD reserve contract
*/
function reserve() external view returns (address);
/**
* @notice ESD governor contract
*/
function governor() external view returns (address);
/**
* @notice ESD timelock contract, owner for the protocol
*/
function timelock() external view returns (address);
/**
* @notice Migration contract to bride v1 assets with current system
*/
function migrator() external view returns (address);
/**
* @notice Registers a new address for USDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setUsdc(address newValue) external;
/**
* @notice Registers a new address for cUSDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setCUsdc(address newValue) external;
/**
* @notice Registers a new address for ESD
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setDollar(address newValue) external;
/**
* @notice Registers a new address for ESDS
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setStake(address newValue) external;
/**
* @notice Registers a new address for the reserve
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setReserve(address newValue) external;
/**
* @notice Registers a new address for the governor
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setGovernor(address newValue) external;
/**
* @notice Registers a new address for the timelock
* @dev Owner only - governance hook
* Does not automatically update the owner of all owned protocol contracts
* @param newValue New address to register
*/
function setTimelock(address newValue) external;
/**
* @notice Registers a new address for the v1 migration contract
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setMigrator(address newValue) external;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title TimeUtils
* @notice Library that accompanies Decimal to convert unix time into Decimal.D256 values
*/
library TimeUtils {
/**
* @notice Number of seconds in a single day
*/
uint256 private constant SECONDS_IN_DAY = 86400;
/**
* @notice Converts an integer number of seconds to a Decimal.D256 amount of days
* @param s Number of seconds to convert
* @return Equivalent amount of days as a Decimal.D256
*/
function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(s, SECONDS_IN_DAY);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title Implementation
* @notice Common functions and accessors across upgradeable, ownable contracts
*/
contract Implementation {
/**
* @notice Emitted when {owner} is updated with `newOwner`
*/
event OwnerUpdate(address newOwner);
/**
* @notice Emitted when {registry} is updated with `newRegistry`
*/
event RegistryUpdate(address newRegistry);
/**
* @dev Storage slot with the address of the current implementation
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Storage slot with the admin of the contract
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1
*/
bytes32 private constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant OWNER_SLOT = keccak256("emptyset.v2.implementation.owner");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant REGISTRY_SLOT = keccak256("emptyset.v2.implementation.registry");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant NOT_ENTERED_SLOT = keccak256("emptyset.v2.implementation.notEntered");
// UPGRADEABILITY
/**
* @notice Returns the current implementation
* @return Address of the current implementation
*/
function implementation() external view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @notice Returns the current proxy admin contract
* @return Address of the current proxy admin contract
*/
function admin() external view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
// REGISTRY
/**
* @notice Updates the registry contract
* @dev Owner only - governance hook
* If registry is already set, the new registry's timelock must match the current's
* @param newRegistry New registry contract
*/
function setRegistry(address newRegistry) external onlyOwner {
IRegistry registry = registry();
// New registry must have identical owner
require(newRegistry != address(0), "Implementation: zero address");
require(
(address(registry) == address(0) && Address.isContract(newRegistry)) ||
IRegistry(newRegistry).timelock() == registry.timelock(),
"Implementation: timelocks must match"
);
_setRegistry(newRegistry);
emit RegistryUpdate(newRegistry);
}
/**
* @notice Updates the registry contract
* @dev Internal only
* @param newRegistry New registry contract
*/
function _setRegistry(address newRegistry) internal {
bytes32 position = REGISTRY_SLOT;
assembly {
sstore(position, newRegistry)
}
}
/**
* @notice Returns the current registry contract
* @return Address of the current registry contract
*/
function registry() public view returns (IRegistry reg) {
bytes32 slot = REGISTRY_SLOT;
assembly {
reg := sload(slot)
}
}
// OWNER
/**
* @notice Takes ownership over a contract if none has been set yet
* @dev Needs to be called initialize ownership after deployment
* Ensure that this has been properly set before using the protocol
*/
function takeOwnership() external {
require(owner() == address(0), "Implementation: already initialized");
_setOwner(msg.sender);
emit OwnerUpdate(msg.sender);
}
/**
* @notice Updates the owner contract
* @dev Owner only - governance hook
* @param newOwner New owner contract
*/
function setOwner(address newOwner) external onlyOwner {
require(newOwner != address(this), "Implementation: this");
require(Address.isContract(newOwner), "Implementation: not contract");
_setOwner(newOwner);
emit OwnerUpdate(newOwner);
}
/**
* @notice Updates the owner contract
* @dev Internal only
* @param newOwner New owner contract
*/
function _setOwner(address newOwner) internal {
bytes32 position = OWNER_SLOT;
assembly {
sstore(position, newOwner)
}
}
/**
* @notice Owner contract with admin permission over this contract
* @return Owner contract
*/
function owner() public view returns (address o) {
bytes32 slot = OWNER_SLOT;
assembly {
o := sload(slot)
}
}
/**
* @dev Only allow when the caller is the owner address
*/
modifier onlyOwner {
require(msg.sender == owner(), "Implementation: not owner");
_;
}
// NON REENTRANT
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(notEntered(), "Implementation: reentrant call");
// Any calls to nonReentrant after this point will fail
_setNotEntered(false);
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_setNotEntered(true);
}
/**
* @notice The entered status of the current call
* @return entered status
*/
function notEntered() internal view returns (bool ne) {
bytes32 slot = NOT_ENTERED_SLOT;
assembly {
ne := sload(slot)
}
}
/**
* @notice Updates the entered status of the current call
* @dev Internal only
* @param newNotEntered New entered status
*/
function _setNotEntered(bool newNotEntered) internal {
bytes32 position = NOT_ENTERED_SLOT;
assembly {
sstore(position, newNotEntered)
}
}
// SETUP
/**
* @notice Hook to surface arbitrary logic to be called after deployment by owner
* @dev Governance hook
* Does not ensure that it is only called once because it is permissioned to governance only
*/
function setup() external onlyOwner {
// 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.
_setNotEntered(true);
_setup();
}
/**
* @notice Override to provide addition setup logic per implementation
*/
function _setup() internal { }
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveTypes
* @notice Contains all reserve state structs
*/
contract ReserveTypes {
/**
* @notice Stores state for a single order
*/
struct Order {
/**
* @notice price (takerAmount per makerAmount) for the order as a Decimal
*/
Decimal.D256 price;
/**
* @notice total available amount of the maker token
*/
uint256 amount;
}
/**
* @notice Stores state for the entire reserve
*/
struct State {
/**
* @notice Total debt
*/
uint256 totalDebt;
/**
* @notice Mapping of total debt per borrower
*/
mapping(address => uint256) debt;
/**
* @notice Mapping of all registered limit orders
*/
mapping(address => mapping(address => ReserveTypes.Order)) orders;
}
}
/**
* @title ReserveState
* @notice Reserve state
*/
contract ReserveState {
/**
* @notice Entirety of the reserve contract state
* @dev To upgrade state, append additional state variables at the end of this contract
*/
ReserveTypes.State internal _state;
}
/**
* @title ReserveAccessors
* @notice Reserve state accessor helpers
*/
contract ReserveAccessors is Implementation, ReserveState {
using SafeMath for uint256;
using Decimal for Decimal.D256;
// SWAPPER
/**
* @notice Full state of the `makerToken`-`takerToken` order
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @return Specified order
*/
function order(address makerToken, address takerToken) public view returns (ReserveTypes.Order memory) {
return _state.orders[makerToken][takerToken];
}
/**
* @notice Returns the total debt outstanding
* @return Total debt
*/
function totalDebt() public view returns (uint256) {
return _state.totalDebt;
}
/**
* @notice Returns the total debt outstanding for `borrower`
* @return Total debt for borrower
*/
function debt(address borrower) public view returns (uint256) {
return _state.debt[borrower];
}
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Internal only
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount to decrement in ESD
*/
function _updateOrder(address makerToken, address takerToken, uint256 price, uint256 amount) internal {
_state.orders[makerToken][takerToken] = ReserveTypes.Order({price: Decimal.D256({value: price}), amount: amount});
}
/**
* @notice Decrements the available amount of the specified `makerToken`-`takerToken` order
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param amount Amount to decrement in ESD
* @param reason revert reason
*/
function _decrementOrderAmount(address makerToken, address takerToken, uint256 amount, string memory reason) internal {
_state.orders[makerToken][takerToken].amount = _state.orders[makerToken][takerToken].amount.sub(amount, reason);
}
/**
* @notice Decrements the debt for `borrower`
* @dev Internal only
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
*/
function _incrementDebt(address borrower, uint256 amount) internal {
_state.totalDebt = _state.totalDebt.add(amount);
_state.debt[borrower] = _state.debt[borrower].add(amount);
}
/**
* @notice Increments the debt for `borrower`
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
* @param reason revert reason
*/
function _decrementDebt(address borrower, uint256 amount, string memory reason) internal {
_state.totalDebt = _state.totalDebt.sub(amount, reason);
_state.debt[borrower] = _state.debt[borrower].sub(amount, reason);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveVault
* @notice Logic to passively manage USDC reserve with low-risk strategies
* @dev Currently uses Compound to lend idle USDC in the reserve
*/
contract ReserveVault is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Decimal for Decimal.D256;
/**
* @notice Emitted when `amount` USDC is supplied to the vault
*/
event SupplyVault(uint256 amount);
/**
* @notice Emitted when `amount` USDC is redeemed from the vault
*/
event RedeemVault(uint256 amount);
/**
* @notice Total value of the assets managed by the vault
* @dev Denominated in USDC
* @return Total value of the vault
*/
function _balanceOfVault() internal view returns (uint256) {
ICErc20 cUsdc = ICErc20(registry().cUsdc());
Decimal.D256 memory exchangeRate = Decimal.D256({value: cUsdc.exchangeRateStored()});
return exchangeRate.mul(cUsdc.balanceOf(address(this))).asUint256();
}
/**
* @notice Supplies `amount` USDC to the external protocol for reward accrual
* @dev Supplies to the Compound USDC lending pool
* @param amount Amount of USDC to supply
*/
function _supplyVault(uint256 amount) internal {
address cUsdc = registry().cUsdc();
IERC20(registry().usdc()).safeApprove(cUsdc, amount);
require(ICErc20(cUsdc).mint(amount) == 0, "ReserveVault: supply failed");
emit SupplyVault(amount);
}
/**
* @notice Redeems `amount` USDC from the external protocol for reward accrual
* @dev Redeems from the Compound USDC lending pool
* @param amount Amount of USDC to redeem
*/
function _redeemVault(uint256 amount) internal {
require(ICErc20(registry().cUsdc()).redeemUnderlying(amount) == 0, "ReserveVault: redeem failed");
emit RedeemVault(amount);
}
/**
* @notice Claims all available governance rewards from the external protocol
* @dev Owner only - governance hook
* Claims COMP accrued from lending on the USDC pool
*/
function claimVault() external onlyOwner {
ICErc20(registry().cUsdc()).comptroller().claimComp(address(this));
}
/**
* @notice Delegates voting power to `delegatee` for `token` governance token held by the reserve
* @dev Owner only - governance hook
* Works for all COMP-based governance tokens
* @param token Governance token to delegate voting power
* @param delegatee Account to receive reserve's voting power
*/
function delegateVault(address token, address delegatee) external onlyOwner {
IGovToken(token).delegate(delegatee);
}
}
/**
* @title ICErc20
* @dev Compound ICErc20 interface
*/
contract ICErc20 {
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint256);
/**
* @notice Get the token balance of the `account`
* @param account The address of the account to query
* @return The number of tokens owned by `account`
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Contract which oversees inter-cToken operations
*/
function comptroller() public view returns (IComptroller);
}
/**
* @title IComptroller
* @dev Compound IComptroller interface
*/
contract IComptroller {
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public;
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveComptroller
* @notice Reserve accounting logic for managing the ESD stablecoin.
*/
contract ReserveComptroller is ReserveAccessors, ReserveVault {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` purchases `mintAmount` ESD from the reserve for `costAmount` USDC
*/
event Mint(address indexed account, uint256 mintAmount, uint256 costAmount);
/**
* @notice Emitted when `account` sells `costAmount` ESD to the reserve for `redeemAmount` USDC
*/
event Redeem(address indexed account, uint256 costAmount, uint256 redeemAmount);
/**
* @notice Emitted when `account` borrows `borrowAmount` ESD from the reserve
*/
event Borrow(address indexed account, uint256 borrowAmount);
/**
* @notice Emitted when `account` repays `repayAmount` ESD to the reserve
*/
event Repay(address indexed account, uint256 repayAmount);
/**
* @notice Helper constant to convert ESD to USDC and vice versa
*/
uint256 private constant USDC_DECIMAL_DIFF = 1e12;
// EXTERNAL
/**
* @notice The total value of the reserve-owned assets denominated in USDC
* @return Reserve total value
*/
function reserveBalance() public view returns (uint256) {
uint256 internalBalance = _balanceOf(registry().usdc(), address(this));
uint256 vaultBalance = _balanceOfVault();
return internalBalance.add(vaultBalance);
}
/**
* @notice The ratio of the {reserveBalance} to total ESD issuance
* @dev Assumes 1 ESD = 1 USDC, normalizing for decimals
* @return Reserve ratio
*/
function reserveRatio() public view returns (Decimal.D256 memory) {
uint256 issuance = _totalSupply(registry().dollar()).sub(totalDebt());
return issuance == 0 ? Decimal.one() : Decimal.ratio(_fromUsdcAmount(reserveBalance()), issuance);
}
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* Equivalent to the current reserve ratio less the current redemption tax (if any)
* @return Current ESD redemption price
*/
function redeemPrice() public view returns (Decimal.D256 memory) {
return Decimal.min(reserveRatio(), Decimal.one());
}
/**
* @notice Mints `amount` ESD to the caller in exchange for an equivalent amount of USDC
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer USDC
* @param amount Amount of ESD to mint
*/
function mint(uint256 amount) external nonReentrant {
uint256 costAmount = _toUsdcAmount(amount);
// Take the ceiling to ensure no "free" ESD is minted
costAmount = _fromUsdcAmount(costAmount) == amount ? costAmount : costAmount.add(1);
_transferFrom(registry().usdc(), msg.sender, address(this), costAmount);
_supplyVault(costAmount);
_mintDollar(msg.sender, amount);
emit Mint(msg.sender, amount, costAmount);
}
/**
* @notice Burns `amount` ESD from the caller in exchange for USDC at the rate of {redeemPrice}
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer ESD
* @param amount Amount of ESD to mint
*/
function redeem(uint256 amount) external nonReentrant {
uint256 redeemAmount = _toUsdcAmount(redeemPrice().mul(amount).asUint256());
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
_redeemVault(redeemAmount);
_transfer(registry().usdc(), msg.sender, redeemAmount);
emit Redeem(msg.sender, amount, redeemAmount);
}
/**
* @notice Lends `amount` ESD to `to` while recording the corresponding debt entry
* @dev Non-reentrant
* Caller must be owner
* Used to pre-fund trusted contracts with ESD without backing (e.g. batchers)
* @param account Address to send the borrowed ESD to
* @param amount Amount of ESD to borrow
*/
function borrow(address account, uint256 amount) external onlyOwner nonReentrant {
require(_canBorrow(account, amount), "ReserveComptroller: cant borrow");
_incrementDebt(account, amount);
_mintDollar(account, amount);
emit Borrow(account, amount);
}
/**
* @notice Repays `amount` ESD on behalf of `to` while reducing its corresponding debt
* @dev Non-reentrant
* @param account Address to repay ESD on behalf of
* @param amount Amount of ESD to repay
*/
function repay(address account, uint256 amount) external nonReentrant {
_decrementDebt(account, amount, "ReserveComptroller: insufficient debt");
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
emit Repay(account, amount);
}
// INTERNAL
/**
* @notice Mints `amount` ESD to `account`
* @dev Internal only
* @param account Account to receive minted ESD
* @param amount Amount of ESD to mint
*/
function _mintDollar(address account, uint256 amount) internal {
address dollar = registry().dollar();
IManagedToken(dollar).mint(amount);
IERC20(dollar).safeTransfer(account, amount);
}
/**
* @notice Burns `amount` ESD held by the reserve
* @dev Internal only
* @param amount Amount of ESD to burn
*/
function _burnDollar(uint256 amount) internal {
IManagedToken(registry().dollar()).burn(amount);
}
/**
* @notice `token` balance of `account`
* @dev Internal only
* @param token Token to get the balance for
* @param account Account to get the balance of
*/
function _balanceOf(address token, address account) internal view returns (uint256) {
return IERC20(token).balanceOf(account);
}
/**
* @notice Total supply of `token`
* @dev Internal only
* @param token Token to get the total supply of
*/
function _totalSupply(address token) internal view returns (uint256) {
return IERC20(token).totalSupply();
}
/**
* @notice Safely transfers `amount` `token` from the caller to `receiver`
* @dev Internal only
* @param token Token to transfer
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transfer(address token, address receiver, uint256 amount) internal {
IERC20(token).safeTransfer(receiver, amount);
}
/**
* @notice Safely transfers `amount` `token` from the `sender` to `receiver`
* @dev Internal only
Requires `amount` allowance from `sender` for caller
* @param token Token to transfer
* @param sender Account to send the tokens
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transferFrom(address token, address sender, address receiver, uint256 amount) internal {
IERC20(token).safeTransferFrom(sender, receiver, amount);
}
/**
* @notice Converts ESD amount to USDC amount
* @dev Private only
* Converts an 18-decimal ERC20 amount to a 6-decimals ERC20 amount
* @param dec18Amount 18-decimal ERC20 amount
* @return 6-decimals ERC20 amount
*/
function _toUsdcAmount(uint256 dec18Amount) internal pure returns (uint256) {
return dec18Amount.div(USDC_DECIMAL_DIFF);
}
/**
* @notice Convert USDC amount to ESD amount
* @dev Private only
* Converts a 6-decimal ERC20 amount to an 18-decimals ERC20 amount
* @param usdcAmount 6-decimal ERC20 amount
* @return 18-decimals ERC20 amount
*/
function _fromUsdcAmount(uint256 usdcAmount) internal pure returns (uint256) {
return usdcAmount.mul(USDC_DECIMAL_DIFF);
}
function _canBorrow(address account, uint256 amount) private view returns (bool) {
uint256 totalBorrowAmount = debt(account).add(amount);
if ( // WrapOnlyBatcher
account == address(0x0B663CeaCEF01f2f88EB7451C70Aa069f19dB997) &&
totalBorrowAmount <= 1_000_000e18
) return true;
return false;
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveSwapper
* @notice Logic for managing outstanding reserve limit orders.
* Since the reserve is autonomous, it cannot use traditional DEXs without being front-run. The `ReserveSwapper`
* allows governance to place outstanding limit orders selling reserve assets in exchange for assets the reserve
* wishes to purchase. This is the main mechanism by which the reserve may diversify itself, or buy back ESDS
* using generated rewards.
*/
contract ReserveSwapper is ReserveComptroller {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `amount` of the `makerToken`-`takerToken` order is registered with price `price`
*/
event OrderRegistered(address indexed makerToken, address indexed takerToken, uint256 price, uint256 amount);
/**
* @notice Emitted when the reserve pays `takerAmount` of `takerToken` in exchange for `makerAmount` of `makerToken`
*/
event Swap(address indexed makerToken, address indexed takerToken, uint256 takerAmount, uint256 makerAmount);
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Owner only - governance hook
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount of the makerToken that reserve wishes to sell - uint256(-1) indicates all reserve funds
*/
function registerOrder(address makerToken, address takerToken, uint256 price, uint256 amount) external onlyOwner {
_updateOrder(makerToken, takerToken, price, amount);
emit OrderRegistered(makerToken, takerToken, price, amount);
}
/**
* @notice Purchases `makerToken` from the reserve in exchange for `takerAmount` of `takerToken`
* @dev Non-reentrant
* Uses the state-defined price for the `makerToken`-`takerToken` order
* Maker and taker tokens must be different
* Cannot swap ESD
* @param makerToken Token that the caller wishes to buy
* @param takerToken Token that the caller wishes to sell
* @param takerAmount Amount of takerToken to sell
*/
function swap(address makerToken, address takerToken, uint256 takerAmount) external nonReentrant {
address dollar = registry().dollar();
require(makerToken != dollar, "ReserveSwapper: unsupported token");
require(takerToken != dollar, "ReserveSwapper: unsupported token");
require(makerToken != takerToken, "ReserveSwapper: tokens equal");
ReserveTypes.Order memory order = order(makerToken, takerToken);
uint256 makerAmount = Decimal.from(takerAmount).div(order.price, "ReserveSwapper: no order").asUint256();
if (order.amount != uint256(-1))
_decrementOrderAmount(makerToken, takerToken, makerAmount, "ReserveSwapper: insufficient amount");
_transferFrom(takerToken, msg.sender, address(this), takerAmount);
_transfer(makerToken, msg.sender, makerAmount);
emit Swap(makerToken, takerToken, takerAmount, makerAmount);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveIssuer
* @notice Logic to manage the supply of ESDS
*/
contract ReserveIssuer is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` mints `amount` of ESDS
*/
event MintStake(address account, uint256 mintAmount);
/**
* @notice Emitted when `amount` of ESDS is burned from the reserve
*/
event BurnStake(uint256 burnAmount);
/**
* @notice Mints new ESDS tokens to a specified `account`
* @dev Non-reentrant
* Owner only - governance hook
* ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation
* Will revert if totalSupply exceeds this maximum
* @param account Account to mint ESDS to
* @param amount Amount of ESDS to mint
*/
function mintStake(address account, uint256 amount) public onlyOwner {
address stake = registry().stake();
IManagedToken(stake).mint(amount);
IERC20(stake).safeTransfer(account, amount);
emit MintStake(account, amount);
}
/**
* @notice Burns all reserve-held ESDS tokens
* @dev Non-reentrant
* Owner only - governance hook
*/
function burnStake() public onlyOwner {
address stake = registry().stake();
uint256 stakeBalance = IERC20(stake).balanceOf(address(this));
IManagedToken(stake).burn(stakeBalance);
emit BurnStake(stakeBalance);
}
}
/*
Copyright 2021 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @title ReserveImpl
* @notice Top-level Reserve contract that extends all other reserve sub-contracts
* @dev This contract should be used an implementation contract for an AdminUpgradeabilityProxy
*/
contract ReserveImpl is IReserve, ReserveComptroller, ReserveIssuer, ReserveSwapper { } | /* @title ReserveTypes @notice Contains all reserve state structs/ | contract ReserveTypes {
Copyright 2021 Empty Set Squad <[email protected]>
struct Order {
Decimal.D256 price;
uint256 amount;
}
struct State {
uint256 totalDebt;
mapping(address => uint256) debt;
mapping(address => mapping(address => ReserveTypes.Order)) orders;
}
}
| 12,066,221 | [
1,
19,
225,
1124,
6527,
2016,
225,
8398,
777,
20501,
919,
8179,
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,
1124,
6527,
2016,
288,
203,
203,
565,
25417,
26599,
21,
8953,
1000,
348,
21733,
411,
5531,
4424,
21733,
36,
685,
1917,
4408,
18,
832,
34,
203,
565,
1958,
4347,
288,
203,
3639,
11322,
18,
40,
5034,
6205,
31,
203,
203,
3639,
2254,
5034,
3844,
31,
203,
203,
565,
289,
203,
565,
1958,
3287,
288,
203,
203,
3639,
2254,
5034,
2078,
758,
23602,
31,
203,
203,
3639,
2874,
12,
2867,
516,
2254,
5034,
13,
18202,
88,
31,
203,
203,
3639,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1124,
6527,
2016,
18,
2448,
3719,
11077,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================ FraxPoolV3 ============================
// ====================================================================
// Allows multiple stablecoins (fixed amount at initialization) as collateral
// LUSD, sUSD, USDP, Wrapped UST, and FEI initially
// For this pool, the goal is to accept crypto-backed / overcollateralized stablecoins to limit
// government / regulatory risk (e.g. USDC blacklisting until holders KYC)
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Dennis: github.com/denett
// Hameed
import "../../Math/SafeMath.sol";
import '../../Uniswap/TransferHelper.sol';
import "../../Staking/Owned.sol";
import "../../FXS/IFxs.sol";
import "../../Frax/IFrax.sol";
import "../../Oracle/AggregatorV3Interface.sol";
import "../../Frax/IFraxAMOMinter.sol";
import "../../ERC20/ERC20.sol";
contract FraxPoolV3 is Owned {
using SafeMath for uint256;
// SafeMath automatically included in Solidity >= 8.0.0
/* ========== STATE VARIABLES ========== */
// Core
address public timelock_address;
address public custodian_address; // Custodian is an EOA (or msig) with pausing privileges only, in case of an emergency
IFrax private FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e);
IFxs private FXS = IFxs(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0);
mapping(address => bool) public amo_minter_addresses; // minter address -> is it enabled
AggregatorV3Interface public priceFeedFRAXUSD = AggregatorV3Interface(0xB9E1E3A9feFf48998E45Fa90847ed4D467E8BcfD);
AggregatorV3Interface public priceFeedFXSUSD = AggregatorV3Interface(0x6Ebc52C8C1089be9eB3945C4350B68B8E4C2233f);
uint256 private chainlink_frax_usd_decimals;
uint256 private chainlink_fxs_usd_decimals;
// Collateral
address[] public collateral_addresses;
string[] public collateral_symbols;
uint256[] public missing_decimals; // Number of decimals needed to get to E18. collateral index -> missing_decimals
uint256[] public pool_ceilings; // Total across all collaterals. Accounts for missing_decimals
uint256[] public collateral_prices; // Stores price of the collateral, if price is paused. CONSIDER ORACLES EVENTUALLY!!!
mapping(address => uint256) public collateralAddrToIdx; // collateral addr -> collateral index
mapping(address => bool) public enabled_collaterals; // collateral address -> is it enabled
// Redeem related
mapping (address => uint256) public redeemFXSBalances;
mapping (address => mapping(uint256 => uint256)) public redeemCollateralBalances; // Address -> collateral index -> balance
uint256[] public unclaimedPoolCollateral; // collateral index -> balance
uint256 public unclaimedPoolFXS;
mapping (address => uint256) public lastRedeemed; // Collateral independent
uint256 public redemption_delay = 2; // Number of blocks to wait before being able to collectRedemption()
uint256 public redeem_price_threshold = 990000; // $0.99
uint256 public mint_price_threshold = 1010000; // $1.01
// Buyback related
mapping(uint256 => uint256) public bbkHourlyCum; // Epoch hour -> Collat out in that hour (E18)
uint256 public bbkMaxColE18OutPerHour = 1000e18;
// Recollat related
mapping(uint256 => uint256) public rctHourlyCum; // Epoch hour -> FXS out in that hour
uint256 public rctMaxFxsOutPerHour = 1000e18;
// Fees and rates
// getters are in collateral_information()
uint256[] private minting_fee;
uint256[] private redemption_fee;
uint256[] private buyback_fee;
uint256[] private recollat_fee;
uint256 public bonus_rate; // Bonus rate on FXS minted during recollateralize(); 6 decimals of precision, set to 0.75% on genesis
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
// Pause variables
// getters are in collateral_information()
bool[] private mintPaused; // Collateral-specific
bool[] private redeemPaused; // Collateral-specific
bool[] private recollateralizePaused; // Collateral-specific
bool[] private buyBackPaused; // Collateral-specific
bool[] private borrowingPaused; // Collateral-specific
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyAMOMinters() {
require(amo_minter_addresses[msg.sender], "Not an AMO Minter");
_;
}
modifier collateralEnabled(uint256 col_idx) {
require(enabled_collaterals[collateral_addresses[col_idx]], "Collateral disabled");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _pool_manager_address,
address _custodian_address,
address _timelock_address,
address[] memory _collateral_addresses,
uint256[] memory _pool_ceilings,
uint256[] memory _initial_fees
) Owned(_pool_manager_address){
// Core
timelock_address = _timelock_address;
custodian_address = _custodian_address;
// Fill collateral info
collateral_addresses = _collateral_addresses;
for (uint256 i = 0; i < _collateral_addresses.length; i++){
// For fast collateral address -> collateral idx lookups later
collateralAddrToIdx[_collateral_addresses[i]] = i;
// Set all of the collaterals initially to disabled
enabled_collaterals[_collateral_addresses[i]] = false;
// Add in the missing decimals
missing_decimals.push(uint256(18).sub(ERC20(_collateral_addresses[i]).decimals()));
// Add in the collateral symbols
collateral_symbols.push(ERC20(_collateral_addresses[i]).symbol());
// Initialize unclaimed pool collateral
unclaimedPoolCollateral.push(0);
// Initialize paused prices to $1 as a backup
collateral_prices.push(PRICE_PRECISION);
// Handle the fees
minting_fee.push(_initial_fees[0]);
redemption_fee.push(_initial_fees[1]);
buyback_fee.push(_initial_fees[2]);
recollat_fee.push(_initial_fees[3]);
// Handle the pauses
mintPaused.push(false);
redeemPaused.push(false);
recollateralizePaused.push(false);
buyBackPaused.push(false);
borrowingPaused.push(false);
}
// Pool ceiling
pool_ceilings = _pool_ceilings;
// Set the decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals();
}
/* ========== STRUCTS ========== */
struct CollateralInformation {
uint256 index;
string symbol;
address col_addr;
bool is_enabled;
uint256 missing_decs;
uint256 price;
uint256 pool_ceiling;
bool mint_paused;
bool redeem_paused;
bool recollat_paused;
bool buyback_paused;
bool borrowing_paused;
uint256 minting_fee;
uint256 redemption_fee;
uint256 buyback_fee;
uint256 recollat_fee;
}
/* ========== VIEWS ========== */
// Helpful for UIs
function collateral_information(address collat_address) external view returns (CollateralInformation memory return_data){
require(enabled_collaterals[collat_address], "Invalid collateral");
// Get the index
uint256 idx = collateralAddrToIdx[collat_address];
return_data = CollateralInformation(
idx, // [0]
collateral_symbols[idx], // [1]
collat_address, // [2]
enabled_collaterals[collat_address], // [3]
missing_decimals[idx], // [4]
collateral_prices[idx], // [5]
pool_ceilings[idx], // [6]
mintPaused[idx], // [7]
redeemPaused[idx], // [8]
recollateralizePaused[idx], // [9]
buyBackPaused[idx], // [10]
borrowingPaused[idx], // [11]
minting_fee[idx], // [12]
redemption_fee[idx], // [13]
buyback_fee[idx], // [14]
recollat_fee[idx] // [15]
);
}
function allCollaterals() external view returns (address[] memory) {
return collateral_addresses;
}
function getFRAXPrice() public view returns (uint256) {
(uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFRAXUSD.latestRoundData();
require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price");
return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_frax_usd_decimals);
}
function getFXSPrice() public view returns (uint256) {
(uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFXSUSD.latestRoundData();
require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price");
return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_fxs_usd_decimals);
}
// Returns the FRAX value in collateral tokens
function getFRAXInCollateral(uint256 col_idx, uint256 frax_amount) public view returns (uint256) {
return frax_amount.mul(PRICE_PRECISION).div(10 ** missing_decimals[col_idx]).div(collateral_prices[col_idx]);
}
// Used by some functions.
function freeCollatBalance(uint256 col_idx) public view returns (uint256) {
return ERC20(collateral_addresses[col_idx]).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]);
}
// Returns dollar value of collateral held in this Frax pool, in E18
function collatDollarBalance() external view returns (uint256 balance_tally) {
balance_tally = 0;
// Test 1
for (uint256 i = 0; i < collateral_addresses.length; i++){
balance_tally += freeCollatBalance(i).mul(10 ** missing_decimals[i]).mul(collateral_prices[i]).div(PRICE_PRECISION);
}
}
function comboCalcBbkRct(uint256 cur, uint256 max, uint256 theo) internal pure returns (uint256) {
if (cur >= max) {
// If the hourly limit has already been reached, return 0;
return 0;
}
else {
// Get the available amount
uint256 available = max.sub(cur);
if (theo >= available) {
// If the the theoretical is more than the available, return the available
return available;
}
else {
// Otherwise, return the theoretical amount
return theo;
}
}
}
// Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio
// Also has throttling to avoid dumps during large price movements
function buybackAvailableCollat() public view returns (uint256) {
uint256 total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
if (global_collateral_ratio > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) {
// Get the theoretical buyback amount
uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18);
// See how much has collateral has been issued this hour
uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()];
// Account for the throttling
return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt);
}
else return 0;
}
// Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio
function recollatTheoColAvailableE18() public view returns (uint256) {
uint256 frax_total_supply = FRAX.totalSupply();
uint256 effective_collateral_ratio = FRAX.globalCollateralValue().mul(PRICE_PRECISION).div(frax_total_supply); // Returns it in 1e6
uint256 desired_collat_e24 = (FRAX.global_collateral_ratio()).mul(frax_total_supply);
uint256 effective_collat_e24 = effective_collateral_ratio.mul(frax_total_supply);
// Return 0 if already overcollateralized
// Otherwise, return the deficiency
if (effective_collat_e24 >= desired_collat_e24) return 0;
else {
return (desired_collat_e24.sub(effective_collat_e24)).div(PRICE_PRECISION);
}
}
// Returns the value of FXS available to be used for recollats
// Also has throttling to avoid dumps during large price movements
function recollatAvailableFxs() public view returns (uint256) {
uint256 fxs_price = getFXSPrice();
// Get the amount of collateral theoretically available
uint256 recollat_theo_available_e18 = recollatTheoColAvailableE18();
// Get the amount of FXS theoretically outputtable
uint256 fxs_theo_out = recollat_theo_available_e18.mul(PRICE_PRECISION).div(fxs_price);
// See how much FXS has been issued this hour
uint256 current_hr_rct = rctHourlyCum[curEpochHr()];
// Account for the throttling
return comboCalcBbkRct(current_hr_rct, rctMaxFxsOutPerHour, fxs_theo_out);
}
// Returns the current epoch hour
function curEpochHr() public view returns (uint256) {
return (block.timestamp / 3600); // Truncation desired
}
/* ========== PUBLIC FUNCTIONS ========== */
function mintFrax(
uint256 col_idx,
uint256 frax_amt,
uint256 frax_out_min,
uint256 max_collat_in,
uint256 max_fxs_in,
bool one_to_one_override
) external collateralEnabled(col_idx) returns (
uint256 total_frax_mint,
uint256 collat_needed,
uint256 fxs_needed
) {
require(mintPaused[col_idx] == false, "Minting is paused");
// Prevent unneccessary mints
require(getFRAXPrice() >= mint_price_threshold, "Frax price too low");
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
if (one_to_one_override || global_collateral_ratio >= PRICE_PRECISION) {
// 1-to-1, overcollateralized, or user selects override
collat_needed = getFRAXInCollateral(col_idx, frax_amt);
fxs_needed = 0;
} else if (global_collateral_ratio == 0) {
// Algorithmic
collat_needed = 0;
fxs_needed = frax_amt.mul(PRICE_PRECISION).div(getFXSPrice());
} else {
// Fractional
uint256 frax_for_collat = frax_amt.mul(global_collateral_ratio).div(PRICE_PRECISION);
uint256 frax_for_fxs = frax_amt.sub(frax_for_collat);
collat_needed = getFRAXInCollateral(col_idx, frax_for_collat);
fxs_needed = frax_for_fxs.mul(PRICE_PRECISION).div(getFXSPrice());
}
// Subtract the minting fee
total_frax_mint = (frax_amt.mul(PRICE_PRECISION.sub(minting_fee[col_idx]))).div(PRICE_PRECISION);
// Check slippages
require((total_frax_mint >= frax_out_min), "FRAX slippage");
require((collat_needed <= max_collat_in), "Collat slippage");
require((fxs_needed <= max_fxs_in), "FXS slippage");
// Check the pool ceiling
require(freeCollatBalance(col_idx).add(collat_needed) <= pool_ceilings[col_idx], "Pool ceiling");
// Take the FXS and collateral first
FXS.pool_burn_from(msg.sender, fxs_needed);
TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collat_needed);
// Mint the FRAX
FRAX.pool_mint(msg.sender, total_frax_mint);
}
function redeemFrax(
uint256 col_idx,
uint256 frax_amount,
uint256 fxs_out_min,
uint256 col_out_min
) external collateralEnabled(col_idx) returns (
uint256 collat_out,
uint256 fxs_out
) {
require(redeemPaused[col_idx] == false, "Redeeming is paused");
// Prevent unneccessary redemptions that could adversely affect the FXS price
require(getFRAXPrice() <= redeem_price_threshold, "Frax price too high");
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 frax_after_fee = (frax_amount.mul(PRICE_PRECISION.sub(redemption_fee[col_idx]))).div(PRICE_PRECISION);
// Assumes $1 FRAX in all cases
if(global_collateral_ratio >= PRICE_PRECISION) {
// 1-to-1 or overcollateralized
collat_out = getFRAXInCollateral(col_idx, frax_after_fee);
fxs_out = 0;
} else if (global_collateral_ratio == 0) {
// Algorithmic
fxs_out = frax_after_fee
.mul(PRICE_PRECISION)
.div(getFXSPrice());
collat_out = 0;
} else {
// Fractional
collat_out = getFRAXInCollateral(col_idx, frax_after_fee)
.mul(global_collateral_ratio)
.div(PRICE_PRECISION);
fxs_out = frax_after_fee
.mul(PRICE_PRECISION.sub(global_collateral_ratio))
.div(getFXSPrice()); // PRICE_PRECISIONS CANCEL OUT
}
// Checks
require(collat_out <= (ERC20(collateral_addresses[col_idx])).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]), "Insufficient pool collateral");
require(collat_out >= col_out_min, "Collateral slippage");
require(fxs_out >= fxs_out_min, "FXS slippage");
// Account for the redeem delay
redeemCollateralBalances[msg.sender][col_idx] = redeemCollateralBalances[msg.sender][col_idx].add(collat_out);
unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].add(collat_out);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_out);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_out);
lastRedeemed[msg.sender] = block.number;
FRAX.pool_burn_from(msg.sender, frax_amount);
FXS.pool_mint(address(this), fxs_out);
}
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption(uint256 col_idx) external returns (uint256 fxs_amount, uint256 collateral_amount) {
require(redeemPaused[col_idx] == false, "Redeeming is paused");
require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Too soon");
bool sendFXS = false;
bool sendCollateral = false;
// Use Checks-Effects-Interactions pattern
if(redeemFXSBalances[msg.sender] > 0){
fxs_amount = redeemFXSBalances[msg.sender];
redeemFXSBalances[msg.sender] = 0;
unclaimedPoolFXS = unclaimedPoolFXS.sub(fxs_amount);
sendFXS = true;
}
if(redeemCollateralBalances[msg.sender][col_idx] > 0){
collateral_amount = redeemCollateralBalances[msg.sender][col_idx];
redeemCollateralBalances[msg.sender][col_idx] = 0;
unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].sub(collateral_amount);
sendCollateral = true;
}
// Send out the tokens
if(sendFXS){
TransferHelper.safeTransfer(address(FXS), msg.sender, fxs_amount);
}
if(sendCollateral){
TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, collateral_amount);
}
}
// Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackFxs(uint256 col_idx, uint256 fxs_amount, uint256 col_out_min) external collateralEnabled(col_idx) returns (uint256 col_out) {
require(buyBackPaused[col_idx] == false, "Buyback is paused");
uint256 fxs_price = getFXSPrice();
uint256 available_excess_collat_dv = buybackAvailableCollat();
// If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral
require(available_excess_collat_dv > 0, "Insuf Collat Avail For BBK");
// Make sure not to take more than is available
uint256 fxs_dollar_value_d18 = fxs_amount.mul(fxs_price).div(PRICE_PRECISION);
require(fxs_dollar_value_d18 <= available_excess_collat_dv, "Insuf Collat Avail For BBK");
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(collateral_prices[col_idx]);
col_out = collateral_equivalent_d18.div(10 ** missing_decimals[col_idx]); // In its natural decimals()
// Subtract the buyback fee
col_out = (col_out.mul(PRICE_PRECISION.sub(buyback_fee[col_idx]))).div(PRICE_PRECISION);
// Check for slippage
require(col_out >= col_out_min, "Collateral slippage");
// Take in and burn the FXS, then send out the collateral
FXS.pool_burn_from(msg.sender, fxs_amount);
TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, col_out);
// Increment the outbound collateral, in E18, for that hour
// Used for buyback throttling
bbkHourlyCum[curEpochHr()] += collateral_equivalent_d18;
}
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralize(uint256 col_idx, uint256 collateral_amount, uint256 fxs_out_min) external collateralEnabled(col_idx) returns (uint256 fxs_out) {
require(recollateralizePaused[col_idx] == false, "Recollat is paused");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals[col_idx]);
uint256 fxs_price = getFXSPrice();
// Get the amount of FXS actually available (accounts for throttling)
uint256 fxs_actually_available = recollatAvailableFxs();
// Calculated the attempted amount of FXS
fxs_out = collateral_amount_d18.mul(PRICE_PRECISION.add(bonus_rate).sub(recollat_fee[col_idx])).div(fxs_price);
// Make sure there is FXS available
require(fxs_out <= fxs_actually_available, "Insuf FXS Avail For RCT");
// Check slippage
require(fxs_out >= fxs_out_min, "FXS slippage");
// Don't take in more collateral than the pool ceiling for this token allows
require(freeCollatBalance(col_idx).add(collateral_amount) <= pool_ceilings[col_idx], "Pool ceiling");
// Take in the collateral and pay out the FXS
TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collateral_amount);
FXS.pool_mint(msg.sender, fxs_out);
// Increment the outbound FXS, in E18
// Used for recollat throttling
rctHourlyCum[curEpochHr()] += fxs_out;
}
// Bypasses the gassy mint->redeem cycle for AMOs to borrow collateral
function amoMinterBorrow(uint256 collateral_amount) external onlyAMOMinters {
// Checks the col_idx of the minter as an additional safety check
uint256 minter_col_idx = IFraxAMOMinter(msg.sender).col_idx();
// Checks to see if borrowing is paused
require(borrowingPaused[minter_col_idx] == false, "Borrowing is paused");
// Ensure collateral is enabled
require(enabled_collaterals[collateral_addresses[minter_col_idx]], "Collateral disabled");
// Transfer
TransferHelper.safeTransfer(collateral_addresses[minter_col_idx], msg.sender, collateral_amount);
}
/* ========== RESTRICTED FUNCTIONS, CUSTODIAN CAN CALL TOO ========== */
function toggleMRBR(uint256 col_idx, uint8 tog_idx) external onlyByOwnGovCust {
if (tog_idx == 0) mintPaused[col_idx] = !mintPaused[col_idx];
else if (tog_idx == 1) redeemPaused[col_idx] = !redeemPaused[col_idx];
else if (tog_idx == 2) buyBackPaused[col_idx] = !buyBackPaused[col_idx];
else if (tog_idx == 3) recollateralizePaused[col_idx] = !recollateralizePaused[col_idx];
else if (tog_idx == 4) borrowingPaused[col_idx] = !borrowingPaused[col_idx];
emit MRBRToggled(col_idx, tog_idx);
}
/* ========== RESTRICTED FUNCTIONS, GOVERNANCE ONLY ========== */
// Add an AMO Minter
function addAMOMinter(address amo_minter_addr) external onlyByOwnGov {
require(amo_minter_addr != address(0), "Zero address detected");
// Make sure the AMO Minter has collatDollarBalance()
uint256 collat_val_e18 = IFraxAMOMinter(amo_minter_addr).collatDollarBalance();
require(collat_val_e18 >= 0, "Invalid AMO");
amo_minter_addresses[amo_minter_addr] = true;
emit AMOMinterAdded(amo_minter_addr);
}
// Remove an AMO Minter
function removeAMOMinter(address amo_minter_addr) external onlyByOwnGov {
amo_minter_addresses[amo_minter_addr] = false;
emit AMOMinterRemoved(amo_minter_addr);
}
function setCollateralPrice(uint256 col_idx, uint256 _new_price) external onlyByOwnGov {
// CONSIDER ORACLES EVENTUALLY!!!
collateral_prices[col_idx] = _new_price;
emit CollateralPriceSet(col_idx, _new_price);
}
// Could also be called toggleCollateral
function toggleCollateral(uint256 col_idx) external onlyByOwnGov {
address col_address = collateral_addresses[col_idx];
enabled_collaterals[col_address] = !enabled_collaterals[col_address];
emit CollateralToggled(col_idx, enabled_collaterals[col_address]);
}
function setPoolCeiling(uint256 col_idx, uint256 new_ceiling) external onlyByOwnGov {
pool_ceilings[col_idx] = new_ceiling;
emit PoolCeilingSet(col_idx, new_ceiling);
}
function setFees(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnGov {
minting_fee[col_idx] = new_mint_fee;
redemption_fee[col_idx] = new_redeem_fee;
buyback_fee[col_idx] = new_buyback_fee;
recollat_fee[col_idx] = new_recollat_fee;
emit FeesSet(col_idx, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee);
}
function setPoolParameters(uint256 new_bonus_rate, uint256 new_redemption_delay) external onlyByOwnGov {
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
emit PoolParametersSet(new_bonus_rate, new_redemption_delay);
}
function setPriceThresholds(uint256 new_mint_price_threshold, uint256 new_redeem_price_threshold) external onlyByOwnGov {
mint_price_threshold = new_mint_price_threshold;
redeem_price_threshold = new_redeem_price_threshold;
emit PriceThresholdsSet(new_mint_price_threshold, new_redeem_price_threshold);
}
function setBbkRctPerHour(uint256 _bbkMaxColE18OutPerHour, uint256 _rctMaxFxsOutPerHour) external onlyByOwnGov {
bbkMaxColE18OutPerHour = _bbkMaxColE18OutPerHour;
rctMaxFxsOutPerHour = _rctMaxFxsOutPerHour;
emit BbkRctPerHourSet(_bbkMaxColE18OutPerHour, _rctMaxFxsOutPerHour);
}
// Set the Chainlink oracles
function setOracles(address _frax_usd_chainlink_addr, address _fxs_usd_chainlink_addr) external onlyByOwnGov {
// Set the instances
priceFeedFRAXUSD = AggregatorV3Interface(_frax_usd_chainlink_addr);
priceFeedFXSUSD = AggregatorV3Interface(_fxs_usd_chainlink_addr);
// Set the decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals();
emit OraclesSet(_frax_usd_chainlink_addr, _fxs_usd_chainlink_addr);
}
function setCustodian(address new_custodian) external onlyByOwnGov {
custodian_address = new_custodian;
emit CustodianSet(new_custodian);
}
function setTimelock(address new_timelock) external onlyByOwnGov {
timelock_address = new_timelock;
emit TimelockSet(new_timelock);
}
/* ========== EVENTS ========== */
event CollateralToggled(uint256 col_idx, bool new_state);
event PoolCeilingSet(uint256 col_idx, uint256 new_ceiling);
event FeesSet(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee);
event PoolParametersSet(uint256 new_bonus_rate, uint256 new_redemption_delay);
event PriceThresholdsSet(uint256 new_bonus_rate, uint256 new_redemption_delay);
event BbkRctPerHourSet(uint256 bbkMaxColE18OutPerHour, uint256 rctMaxFxsOutPerHour);
event AMOMinterAdded(address amo_minter_addr);
event AMOMinterRemoved(address amo_minter_addr);
event OraclesSet(address frax_usd_chainlink_addr, address fxs_usd_chainlink_addr);
event CustodianSet(address new_custodian);
event TimelockSet(address new_timelock);
event MRBRToggled(uint256 col_idx, uint8 tog_idx);
event CollateralPriceSet(uint256 col_idx, uint256 new_price);
} | Check the pool ceiling | require(freeCollatBalance(col_idx).add(collat_needed) <= pool_ceilings[col_idx], "Pool ceiling");
| 12,741,533 | [
1,
1564,
326,
2845,
5898,
4973,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
9156,
914,
4801,
13937,
12,
1293,
67,
3465,
2934,
1289,
12,
1293,
4801,
67,
17471,
13,
1648,
2845,
67,
311,
330,
899,
63,
1293,
67,
3465,
6487,
315,
2864,
5898,
4973,
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
] |
./partial_match/1/0xf20c92fAE68c4ad05A07cEfd64fa844780d9EA58/sources/contracts/SpartanMinter.sol | * @notice the public function validating addresses @param proof_ hashes validating that a leaf exists inside merkle tree aka _merkleRoot @param mintId_ Id sent from the db to check it this token number is minted or not/ | function isAllowedToMint(bytes32[] memory proof_, bytes16 mintId_)
internal
view
returns (bool)
{
require(
MerkleProof.verify(
proof_,
_merkleRoot,
keccak256(abi.encodePacked(mintId_))
),
"SPTN: Please register before minting"
);
return true;
}
| 4,265,097 | [
1,
5787,
1071,
445,
18075,
6138,
225,
14601,
67,
9869,
18075,
716,
279,
7839,
1704,
4832,
30235,
2151,
28105,
389,
6592,
15609,
2375,
225,
312,
474,
548,
67,
3124,
3271,
628,
326,
1319,
358,
866,
518,
333,
1147,
1300,
353,
312,
474,
329,
578,
486,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
21956,
774,
49,
474,
12,
3890,
1578,
8526,
3778,
14601,
67,
16,
1731,
2313,
312,
474,
548,
67,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
31827,
20439,
18,
8705,
12,
203,
7734,
14601,
67,
16,
203,
7734,
389,
6592,
15609,
2375,
16,
203,
7734,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
81,
474,
548,
67,
3719,
203,
5411,
262,
16,
203,
5411,
315,
55,
1856,
50,
30,
7801,
1744,
1865,
312,
474,
310,
6,
203,
3639,
11272,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.10;
// Miners create Elixor (EXOR), which they then convert to Elixir (ELIX)
contract elixor {
string public name;
string public symbol;
uint8 public decimals;
uint256 public startTime;
uint256 public totalSupply;
bool public balanceImportsComplete;
mapping (address => bool) public numRewardsAvailableSetForChildAddress;
mapping (address => bool) public isNewParent;
mapping (address => address) public returnChildForParentNew;
bool public genesisImportsComplete;
// Until contract is locked, devs can freeze the system if anything arises.
// Then deploy a contract that interfaces with the state of this one.
bool public frozen;
bool public freezeProhibited;
address public devAddress; // For doing imports
bool importsComplete; // Locked when devs have updated all balances
mapping (address => uint256) public burnAmountAllowed;
mapping(address => mapping (address => uint256)) allowed;
// Balances for each account
mapping(address => uint256) balances;
mapping (address => uint256) public numRewardsAvailable;
// ELIX address info
bool public ELIXAddressSet;
address public ELIXAddress;
event Transfer(address indexed from, address indexed to, uint256 value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function elixor() {
name = "elixor";
symbol = "EXOR";
decimals = 18;
startTime=1500307354; //Time contract went online.
devAddress=0x85196Da9269B24bDf5FfD2624ABB387fcA05382B; // Set the dev import address
// Dev will create 10 batches as test using 1 EXOR in dev address (which is a child)
// Also will send tiny amounts to several random addresses to make sure parent-child auth works.
// Then set numRewardsAvailable to 0
balances[devAddress]+=1000000000000000000;
totalSupply+=1000000000000000000;
numRewardsAvailableSetForChildAddress[devAddress]=true;
numRewardsAvailable[devAddress]=10;
}
// Returns balance of particular account
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) {
if (!frozen){
if (balances[msg.sender] < _value) revert();
if (balances[_to] + _value < balances[_to]) revert();
if (returnIsParentAddress(_to) || isNewParent[_to]) {
if ((msg.sender==returnChildAddressForParent(_to)) || (returnChildForParentNew[_to]==msg.sender)) {
if (numRewardsAvailableSetForChildAddress[msg.sender]==false) {
setNumRewardsAvailableForAddress(msg.sender);
}
if (numRewardsAvailable[msg.sender]>0) {
uint256 currDate=block.timestamp;
uint256 returnMaxPerBatchGenerated=5000000000000000000000; //max 5000 coins per batch
uint256 deployTime=10*365*86400; //10 years
uint256 secondsSinceStartTime=currDate-startTime;
uint256 maximizationTime=deployTime+startTime;
uint256 coinsPerBatchGenerated;
if (currDate>=maximizationTime) {
coinsPerBatchGenerated=returnMaxPerBatchGenerated;
} else {
uint256 b=(returnMaxPerBatchGenerated/4);
uint256 m=(returnMaxPerBatchGenerated-b)/deployTime;
coinsPerBatchGenerated=secondsSinceStartTime*m+b;
}
numRewardsAvailable[msg.sender]-=1;
balances[msg.sender]+=coinsPerBatchGenerated;
totalSupply+=coinsPerBatchGenerated;
}
}
}
if (_to==ELIXAddress) {
//They want to convert to ELIX
convertToELIX(_value,msg.sender);
}
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (!frozen){
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
if (_to==ELIXAddress) {
//They want to convert to ELIX
convertToELIX(_amount,msg.sender);
}
balances[_to] += _amount;
return true;
} else {
return false;
}
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// Allows devs to set num rewards used. Locked up when system online.
function setNumRewardsAvailableForAddresses(uint256[] numRewardsAvailableForAddresses,address[] addressesToSetFor) {
if (tx.origin==devAddress) { // Dev address
if (!importsComplete) {
for (uint256 i=0;i<addressesToSetFor.length;i++) {
address addressToSet=addressesToSetFor[i];
numRewardsAvailable[addressToSet]=numRewardsAvailableForAddresses[i];
}
}
}
}
// Freezes the entire system
function freezeTransfers() {
if (tx.origin==devAddress) { // Dev address
if (!freezeProhibited) {
frozen=true;
}
}
}
// Prevent Freezing (Once system is ready to be locked)
function prohibitFreeze() {
if (tx.origin==devAddress) { // Dev address
freezeProhibited=true;
}
}
// Get whether address is genesis parent
function returnIsParentAddress(address possibleParent) returns(bool) {
return tme(0xEe22430595aE400a30FFBA37883363Fbf293e24e).parentAddress(possibleParent);
}
// Return child address for parent
function returnChildAddressForParent(address parent) returns(address) {
return tme(0xEe22430595aE400a30FFBA37883363Fbf293e24e).returnChildAddressForParent(parent);
}
//Allows dev to set ELIX Address
function setELIXAddress(address ELIXAddressToSet) {
if (tx.origin==devAddress) { // Dev address
if (!ELIXAddressSet) {
ELIXAddressSet=true;
ELIXAddress=ELIXAddressToSet;
}
}
}
// Conversion to ELIX function
function convertToELIX(uint256 amount,address sender) private {
totalSupply-=amount;
burnAmountAllowed[sender]=amount;
elixir(ELIXAddress).createAmountFromEXORForAddress(amount,sender);
burnAmountAllowed[sender]=0;
}
function returnAmountOfELIXAddressCanProduce(address producingAddress) public returns(uint256) {
return burnAmountAllowed[producingAddress];
}
// Locks up all changes to balances
function lockBalanceChanges() {
if (tx.origin==devAddress) { // Dev address
balanceImportsComplete=true;
}
}
function importGenesisPairs(address[] parents,address[] children) public {
if (tx.origin==devAddress) { // Dev address
if (!genesisImportsComplete) {
for (uint256 i=0;i<parents.length;i++) {
address child=children[i];
address parent=parents[i];
// Set the parent as parent address
isNewParent[parent]=true; // Exciting
// Set the child of that parent
returnChildForParentNew[parent]=child;
balances[child]+=1000000000000000000;
totalSupply+=1000000000000000000;
numRewardsAvailable[child]=10;
numRewardsAvailableSetForChildAddress[child]=true;
}
}
}
}
function lockGenesisImports() public {
if (tx.origin==devAddress) {
genesisImportsComplete=true;
}
}
// Devs will upload balances snapshot of blockchain via this function.
function importAmountForAddresses(uint256[] amounts,address[] addressesToAddTo) public {
if (tx.origin==devAddress) { // Dev address
if (!balanceImportsComplete) {
for (uint256 i=0;i<addressesToAddTo.length;i++) {
address addressToAddTo=addressesToAddTo[i];
uint256 amount=amounts[i];
balances[addressToAddTo]+=amount;
totalSupply+=amount;
}
}
}
}
// Extra balance removal in case any issues arise. Do not anticipate using this function.
function removeAmountForAddresses(uint256[] amounts,address[] addressesToRemoveFrom) public {
if (tx.origin==devAddress) { // Dev address
if (!balanceImportsComplete) {
for (uint256 i=0;i<addressesToRemoveFrom.length;i++) {
address addressToRemoveFrom=addressesToRemoveFrom[i];
uint256 amount=amounts[i];
balances[addressToRemoveFrom]-=amount;
totalSupply-=amount;
}
}
}
}
// Manual override in case any issues arise. Do not anticipate using this function.
function manuallySetNumRewardsAvailableForChildAddress(address addressToSet,uint256 rewardsAvail) public {
if (tx.origin==devAddress) { // Dev address
if (!genesisImportsComplete) {
numRewardsAvailable[addressToSet]=rewardsAvail;
numRewardsAvailableSetForChildAddress[addressToSet]=true;
}
}
}
// Manual override for total supply in case any issues arise. Do not anticipate using this function.
function removeFromTotalSupply(uint256 amount) public {
if (tx.origin==devAddress) { // Dev address
if (!balanceImportsComplete) {
totalSupply-=amount;
}
}
}
function setNumRewardsAvailableForAddress(address addressToSet) private {
//Get the number of rewards used in the old contract
tme tmeContract=tme(0xEe22430595aE400a30FFBA37883363Fbf293e24e);
uint256 numRewardsUsed=tmeContract.numRewardsUsed(addressToSet);
numRewardsAvailable[addressToSet]=10-numRewardsUsed;
numRewardsAvailableSetForChildAddress[addressToSet]=true;
}
}
// Pulling info about parent-child pairs from the original contract
contract tme {
function parentAddress(address possibleParent) public returns(bool);
function returnChildAddressForParent(address parentAddressOfChild) public returns(address);
function numRewardsUsed(address childAddress) public returns(uint256);
}
contract elixir {
function createAmountFromEXORForAddress(uint256 amount,address sender);
} | They want to convert to ELIX | function transfer(address _to, uint256 _value) {
if (!frozen){
if (balances[msg.sender] < _value) revert();
if (balances[_to] + _value < balances[_to]) revert();
if (returnIsParentAddress(_to) || isNewParent[_to]) {
if ((msg.sender==returnChildAddressForParent(_to)) || (returnChildForParentNew[_to]==msg.sender)) {
if (numRewardsAvailableSetForChildAddress[msg.sender]==false) {
setNumRewardsAvailableForAddress(msg.sender);
}
if (numRewardsAvailable[msg.sender]>0) {
uint256 currDate=block.timestamp;
uint256 secondsSinceStartTime=currDate-startTime;
uint256 maximizationTime=deployTime+startTime;
uint256 coinsPerBatchGenerated;
if (currDate>=maximizationTime) {
coinsPerBatchGenerated=returnMaxPerBatchGenerated;
uint256 b=(returnMaxPerBatchGenerated/4);
uint256 m=(returnMaxPerBatchGenerated-b)/deployTime;
coinsPerBatchGenerated=secondsSinceStartTime*m+b;
}
numRewardsAvailable[msg.sender]-=1;
balances[msg.sender]+=coinsPerBatchGenerated;
totalSupply+=coinsPerBatchGenerated;
}
}
}
if (_to==ELIXAddress) {
convertToELIX(_value,msg.sender);
}
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
}
| 1,064,010 | [
1,
1315,
402,
2545,
358,
1765,
358,
512,
2053,
60,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
915,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
288,
225,
203,
430,
16051,
28138,
15329,
203,
377,
203,
565,
309,
261,
70,
26488,
63,
3576,
18,
15330,
65,
411,
389,
1132,
13,
15226,
5621,
203,
565,
309,
261,
70,
26488,
63,
67,
869,
65,
397,
389,
1132,
411,
324,
26488,
63,
67,
869,
5717,
15226,
5621,
203,
203,
565,
309,
261,
2463,
2520,
3054,
1887,
24899,
869,
13,
747,
10783,
3054,
63,
67,
869,
5717,
377,
288,
203,
3639,
309,
14015,
3576,
18,
15330,
631,
2463,
1763,
1887,
20374,
24899,
869,
3719,
747,
261,
2463,
1763,
20374,
1908,
63,
67,
869,
65,
631,
3576,
18,
15330,
3719,
225,
288,
203,
2398,
203,
5411,
309,
261,
2107,
17631,
14727,
5268,
694,
1290,
1763,
1887,
63,
3576,
18,
15330,
65,
631,
5743,
13,
225,
288,
203,
7734,
444,
2578,
17631,
14727,
5268,
1290,
1887,
12,
3576,
18,
15330,
1769,
203,
5411,
289,
203,
203,
5411,
309,
261,
2107,
17631,
14727,
5268,
63,
3576,
18,
15330,
65,
34,
20,
13,
565,
288,
203,
7734,
2254,
5034,
4306,
1626,
33,
2629,
18,
5508,
31,
203,
7734,
2254,
5034,
3974,
9673,
13649,
33,
17016,
1626,
17,
1937,
950,
31,
203,
7734,
2254,
5034,
30547,
1588,
950,
33,
12411,
950,
15,
1937,
950,
31,
203,
7734,
2254,
5034,
276,
9896,
2173,
4497,
7823,
31,
203,
7734,
309,
261,
17016,
1626,
34,
33,
1896,
381,
1588,
950,
13,
225,
288,
203,
10792,
276,
9896,
2173,
4497,
7823,
33,
2463,
2747,
2173,
4497,
7823,
31,
203,
10792,
2254,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-11-19
*/
// File: contracts/IERC2612Permit.sol
pragma solidity 0.7.4;
/**
* @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 IERC2612Permit {
/**
* @dev Sets `amount` 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:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current ERC2612 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);
}
// File: @openzeppelin/contracts/utils/Address.sol
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);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: contracts/ERC20Permit.sol
pragma solidity 0.7.4;
abstract contract ERC20Permit is ERC20Burnable, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() internal {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
/**
* @dev See {IERC2612Permit-permit}.
*
*/
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct = keccak256(
abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)
);
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
/**
* @dev See {IERC2612Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
// File: contracts/CoinPokerChipsToken.sol
pragma solidity 0.7.4;
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol";
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
/**
* @title Token
* @dev Burnable ERC20 Token
*/
contract CoinPokerChipsToken is ERC20Permit, Ownable {
uint256 public constant MAX_CAP = 354786434702574732562458800;
address public governance;
event RecoverToken(address indexed token, address indexed destination, uint256 indexed amount);
modifier onlyGovernance() {
require(msg.sender == governance, "!governance");
_;
}
constructor() ERC20("CoinPoker Chips", "CHP") {
governance = msg.sender;
_mint(governance, MAX_CAP);
}
/**
* @notice Function to set governance contract
* Owner is assumed to be governance
* @param _governance Address of governance contract
*/
function setGovernance(address _governance) public onlyGovernance {
governance = _governance;
}
/**
* @notice Function to recover funds
* Owner is assumed to be governance or trusted party for helping users
* @param token Address of token to be rescued
* @param destination User address
* @param amount Amount of tokens
*/
function recoverToken(
address token,
address destination,
uint256 amount
) external onlyGovernance {
require(token != destination, "Invalid address");
require(IERC20(token).transfer(destination, amount), "Retrieve failed");
emit RecoverToken(token, destination, amount);
}
} | * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in 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 IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
| 7,808,198 | [
1,
1358,
434,
326,
4232,
39,
3462,
13813,
305,
2710,
15632,
6617,
4524,
358,
506,
7165,
3970,
14862,
16,
487,
2553,
316,
15605,
326,
288,
457,
1938,
97,
707,
16,
1492,
848,
506,
1399,
358,
2549,
392,
2236,
1807,
4232,
39,
3462,
1699,
1359,
261,
5946,
288,
45,
654,
39,
3462,
17,
5965,
1359,
6792,
635,
3430,
310,
279,
883,
6726,
635,
326,
2236,
18,
2525,
486,
283,
6291,
603,
21016,
45,
654,
39,
3462,
17,
12908,
537,
97,
9191,
326,
1147,
10438,
2236,
3302,
1404,
1608,
358,
1366,
279,
2492,
16,
471,
12493,
353,
486,
1931,
358,
6887,
512,
1136,
622,
777,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
654,
39,
5558,
2138,
9123,
305,
288,
203,
565,
445,
21447,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
14096,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
1661,
764,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
contract CompetitionFactory {
// ------ Contract member variables ------
struct Competition {
uint prize; // prize in ether (units are 'wei' so values are large: can't use uint32)
uint deadline; // end of competition (denoted in Epoch Time)
address host; // address of host
address winner; // address of winner
string dataset; // ipfs hash of host dataset (with test targets).
}
mapping (uint => mapping (address => string)) public competitionToParticipants; // competition id -> address of participant -> ipfs hash of a participant predictions
Competition[] public competitions; // vector of all competitions (past and present)
address[] public leaderboard; // leaderboard of all winners
event ContractDeployed (uint _competitionId, address _person, string _hash, uint _cost, uint _time);
event NewCompetition (uint _competitionId, address _person, string _hash, uint _cost, uint _time);
event NewSubmission (uint _competitionId, address _person, string _hash, uint _cost, uint _time);
event NewPayout (uint _competitionId, address _person, string _hash, uint _cost, uint _time);
// ------ Contract functions ------
// Fallback function, allows this contract to receive ether.
function () public payable {}
// Constructor
function CompetitionFactory() {
ContractDeployed(0, msg.sender,"", msg.value, now);
}
// Function to create a new competition and add it to the list (winner is defaulted to host).
function createCompetition(string _dataset, uint _deadline) public payable returns (uint _competitionId) {
//if (_deadline <= now) throw;
_competitionId = competitions.push(Competition(msg.value, _deadline, msg.sender, msg.sender, _dataset)) - 1;
NewCompetition(_competitionId, msg.sender, _dataset, msg.value, now);
}
// Modifier that requires the competitionId to be a valid/existing one.
modifier competitionIdCheck(uint _competitionId) {
//if (_competitionId >= competitions.length) throw;
_;
}
// Function for participants to submit the IPFS hash of their prediction data for a specific competition.
function submitIPFSHash(string _ipfsHash, uint _competitionId) external competitionIdCheck(_competitionId) {
//if (now >= competitions[_competitionId].deadline) throw;
competitionToParticipants[_competitionId][msg.sender] = _ipfsHash;
NewSubmission(_competitionId, msg.sender, _ipfsHash, msg.value, now);
}
// Function to execute the payouts of a competition.
function executePayouts(uint _competitionId, address _winner) external competitionIdCheck(_competitionId) {
Competition storage myCompetition = competitions[_competitionId];
//if (now <= myCompetition.deadline) throw;
// Determine the winner of a competition and transfer the prize, but throw if transfer fails.
_determineWinner(_winner, _competitionId, myCompetition);
if (!myCompetition.winner.send(myCompetition.prize)) throw;
// Update leaderboard.
leaderboard.push(myCompetition.winner);
NewPayout(_competitionId, myCompetition.winner, competitionToParticipants[_competitionId][myCompetition.winner], myCompetition.prize, now);
}
// TODO: winner should be calculated by an iExec oracle here, but for now the logloss is calculated off-chain and the winner passed in as an argument (from executePayouts()).
function _determineWinner(address _winner, uint /*_competitionId*/, Competition storage _competition) private {
_competition.winner = _winner;
}
// Get the dataset of a competition.
function getDataset(uint _competitionId) external competitionIdCheck(_competitionId) returns (string) {
return competitions[_competitionId].dataset;
}
// Get the deadline of a competition.
function getDeadline(uint _competitionId) external competitionIdCheck(_competitionId) returns (uint) {
return competitions[_competitionId].deadline;
}
// Get the prize of a competition.
function getPrize(uint _competitionId) external competitionIdCheck(_competitionId) returns (uint) {
return competitions[_competitionId].prize;
}
// Get the winner of a competition.
function getWinner(uint _competitionId) external competitionIdCheck(_competitionId) returns (string) {
return toAsciiString(competitions[_competitionId].winner);
}
// Get the host of a competition.
function getHost(uint _competitionId) external competitionIdCheck(_competitionId) returns (address) {
return competitions[_competitionId].host;
}
// Get a participant's ipfs hash for a competition.
function getParticipantIPFSHash(uint _competitionId, address _participantAddress) external competitionIdCheck(_competitionId) returns (string) {
return competitionToParticipants[_competitionId][_participantAddress];
}
// Get a competition by id.
function getCompetition(uint _competitionId) external competitionIdCheck(_competitionId) returns (uint, uint) {
Competition memory cmp = competitions[_competitionId];
return (cmp.prize, cmp.deadline);
}
// Get the leaderboard of winners.
function getLeaderboard() external returns (address[]) {
return leaderboard;
}
// Function to convert from an address to a string representation.
function toAsciiString(address x) returns (string) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte b = byte(uint8(uint(x) / (2**(8*(19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
// Function to convert a byte into a char.
function char(byte b) returns (byte c) {
if (b < 10)
return byte(uint8(b) + 0x30);
return byte(uint8(b) + 0x57);
}
} | Modifier that requires the competitionId to be a valid/existing one.if (_competitionId >= competitions.length) throw; | modifier competitionIdCheck(uint _competitionId) {
_;
}
| 14,105,174 | [
1,
9829,
716,
4991,
326,
25163,
608,
548,
358,
506,
279,
923,
19,
11711,
1245,
18,
430,
261,
67,
31942,
608,
548,
1545,
25163,
5029,
18,
2469,
13,
604,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
9606,
25163,
608,
548,
1564,
12,
11890,
389,
31942,
608,
548,
13,
288,
203,
565,
389,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Community vote
* @notice An oracle for relevant decisions made by the community.
*/
contract CommunityVote is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => bool) doubleSpenderByWallet;
uint256 maxDriipNonce;
uint256 maxNullNonce;
bool dataAvailable;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
dataAvailable = true;
}
//
// Results functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the max driip nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxDriipNonce()
public
view
returns (uint256)
{
return maxDriipNonce;
}
/// @notice Get the max null settlement nonce to be accepted in settlements
/// @return the max driip nonce
function getMaxNullNonce()
public
view
returns (uint256)
{
return maxNullNonce;
}
/// @notice Get the data availability status
/// @return true if data is available
function isDataAvailable()
public
view
returns (bool)
{
return dataAvailable;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title CommunityVotable
* @notice An ownable that has a community vote property
*/
contract CommunityVotable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
CommunityVote public communityVote;
bool public communityVoteFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote);
event FreezeCommunityVoteEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the community vote contract
/// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote)
public
onlyDeployer
notNullAddress(address(newCommunityVote))
notSameAddresses(address(newCommunityVote), address(communityVote))
{
require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]");
// Set new community vote
CommunityVote oldCommunityVote = communityVote;
communityVote = newCommunityVote;
// Emit event
emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote);
}
/// @notice Freeze the community vote from further updates
/// @dev This operation can not be undone
function freezeCommunityVote()
public
onlyDeployer
{
communityVoteFrozen = true;
// Emit event
emit FreezeCommunityVoteEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier communityVoteInitialized() {
require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that contains registered beneficiaries
*/
contract Benefactor is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Beneficiary[] public beneficiaries;
mapping(address => uint256) public beneficiaryIndexByAddress;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterBeneficiaryEvent(Beneficiary beneficiary);
event DeregisterBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given beneficiary
/// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] > 0)
return false;
beneficiaries.push(beneficiary);
beneficiaryIndexByAddress[_beneficiary] = beneficiaries.length;
// Emit event
emit RegisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Deregister the given beneficiary
/// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
address _beneficiary = address(beneficiary);
if (beneficiaryIndexByAddress[_beneficiary] == 0)
return false;
uint256 idx = beneficiaryIndexByAddress[_beneficiary] - 1;
if (idx < beneficiaries.length - 1) {
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1];
beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
}
beneficiaries.length--;
beneficiaryIndexByAddress[_beneficiary] = 0;
// Emit event
emit DeregisterBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Gauge whether the given address is the one of a registered beneficiary
/// @param beneficiary Address of beneficiary
/// @return true if beneficiary is registered, else false
function isRegisteredBeneficiary(Beneficiary beneficiary)
public
view
returns (bool)
{
return beneficiaryIndexByAddress[address(beneficiary)] > 0;
}
/// @notice Get the count of registered beneficiaries
/// @return The count of registered beneficiaries
function registeredBeneficiariesCount()
public
view
returns (uint256)
{
return beneficiaries.length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBenefactor
* @notice A benefactor whose registered beneficiaries obtain a predefined fraction of total amount
*/
contract AccrualBenefactor is Benefactor {
using SafeMathIntLib for int256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => int256) private _beneficiaryFractionMap;
int256 public totalBeneficiaryFraction;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterAccrualBeneficiaryEvent(Beneficiary beneficiary, int256 fraction);
event DeregisterAccrualBeneficiaryEvent(Beneficiary beneficiary);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Register the given accrual beneficiary for the entirety fraction
/// @param beneficiary Address of accrual beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
return registerFractionalBeneficiary(AccrualBeneficiary(address(beneficiary)), ConstantsLib.PARTS_PER());
}
/// @notice Register the given accrual beneficiary for the given fraction
/// @param beneficiary Address of accrual beneficiary to be registered
/// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]");
require(
totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER(),
"Total beneficiary fraction out of bounds [AccrualBenefactor.sol:60]"
);
if (!super.registerBeneficiary(beneficiary))
return false;
_beneficiaryFractionMap[address(beneficiary)] = fraction;
totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction);
// Emit event
emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction);
return true;
}
/// @notice Deregister the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary)
public
onlyDeployer
notNullAddress(address(beneficiary))
returns (bool)
{
if (!super.deregisterBeneficiary(beneficiary))
return false;
address _beneficiary = address(beneficiary);
totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[_beneficiary]);
_beneficiaryFractionMap[_beneficiary] = 0;
// Emit event
emit DeregisterAccrualBeneficiaryEvent(beneficiary);
return true;
}
/// @notice Get the fraction of benefits that is granted the given accrual beneficiary
/// @param beneficiary Address of accrual beneficiary
/// @return The beneficiary's fraction
function beneficiaryFraction(AccrualBeneficiary beneficiary)
public
view
returns (int256)
{
return _beneficiaryFractionMap[address(beneficiary)];
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title RevenueFund
* @notice The target of all revenue earned in driip settlements and from which accrued revenue is split amongst
* accrual beneficiaries.
*/
contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance periodAccrual;
CurrenciesLib.Currencies periodCurrencies;
FungibleBalanceLib.Balance aggregateAccrual;
CurrenciesLib.Currencies aggregateCurrencies;
TxHistoryLib.TxHistory private txHistory;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event CloseAccrualPeriodEvent();
event RegisterServiceEvent(address service);
event DeregisterServiceEvent(address service);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balances
periodAccrual.add(amount, address(0), 0);
aggregateAccrual.add(amount, address(0), 0);
// Add currency to stores of currencies
periodCurrencies.add(address(0), 0);
aggregateCurrencies.add(address(0), 0);
// Add to transaction history
txHistory.addDeposit(amount, address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount,
address currencyCt, uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [RevenueFund.sol:124]");
// Add to balances
periodAccrual.add(amount, currencyCt, currencyId);
aggregateAccrual.add(amount, currencyCt, currencyId);
// Add currency to stores of currencies
periodCurrencies.add(currencyCt, currencyId);
aggregateCurrencies.add(currencyCt, currencyId);
// Add to transaction history
txHistory.addDeposit(amount, currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the period accrual balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The current period's accrual balance
function periodAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return periodAccrual.get(currencyCt, currencyId);
}
/// @notice Get the aggregate accrual balance of the given currency, including contribution from the
/// current accrual period
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The aggregate accrual balance
function aggregateAccrualBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return aggregateAccrual.get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded in the accrual period
/// @return The number of currencies in the current accrual period
function periodCurrenciesCount()
public
view
returns (uint256)
{
return periodCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range in the current accrual period
function periodCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return periodCurrencies.getByIndices(low, up);
}
/// @notice Get the count of currencies ever recorded
/// @return The number of currencies ever recorded
function aggregateCurrenciesCount()
public
view
returns (uint256)
{
return aggregateCurrencies.count();
}
/// @notice Get the currencies with indices in the given range that have ever been recorded
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range ever recorded
function aggregateCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return aggregateCurrencies.getByIndices(low, up);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Close the current accrual period of the given currencies
/// @param currencies The concerned currencies
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory currencies)
public
onlyOperator
{
require(
ConstantsLib.PARTS_PER() == totalBeneficiaryFraction,
"Total beneficiary fraction out of bounds [RevenueFund.sol:236]"
);
// Execute transfer
for (uint256 i = 0; i < currencies.length; i++) {
MonetaryTypesLib.Currency memory currency = currencies[i];
int256 remaining = periodAccrual.get(currency.ct, currency.id);
if (0 >= remaining)
continue;
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
if (beneficiaryFraction(beneficiary) > 0) {
int256 transferable = periodAccrual.get(currency.ct, currency.id)
.mul(beneficiaryFraction(beneficiary))
.div(ConstantsLib.PARTS_PER());
if (transferable > remaining)
transferable = remaining;
if (transferable > 0) {
// Transfer ETH to the beneficiary
if (currency.ct == address(0))
beneficiary.receiveEthersTo.value(uint256(transferable))(address(0), "");
// Transfer token to the beneficiary
else {
TransferController controller = transferController(currency.ct, "");
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(transferable), currency.ct, currency.id
)
);
require(success, "Approval by controller failed [RevenueFund.sol:274]");
beneficiary.receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, "");
}
remaining = remaining.sub(transferable);
}
}
}
// Roll over remaining to next accrual period
periodAccrual.set(remaining, currency.ct, currency.id);
}
// Close accrual period of accrual beneficiaries
for (uint256 j = 0; j < beneficiaries.length; j++) {
AccrualBeneficiary beneficiary = AccrualBeneficiary(address(beneficiaries[j]));
// Require that beneficiary fraction is strictly positive
if (0 >= beneficiaryFraction(beneficiary))
continue;
// Close accrual period
beneficiary.closeAccrualPeriod(currencies);
}
// Emit event
emit CloseAccrualPeriodEvent();
}
}
/**
* Strings Library
*
* In summary this is a simple library of string functions which make simple
* string operations less tedious in solidity.
*
* Please be aware these functions can be quite gas heavy so use them only when
* necessary not to clog the blockchain with expensive transactions.
*
* @author James Lockhart <[email protected]>
*/
library Strings {
/**
* Concat (High gas cost)
*
* Appends two strings together and returns a new value
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string which will be the concatenated
* prefix
* @param _value The value to be the concatenated suffix
* @return string The resulting string from combinging the base and value
*/
function concat(string memory _base, string memory _value)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length > 0);
string memory _tmpValue = new string(_baseBytes.length +
_valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for (i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for (i = 0; i < _valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function indexOf(string memory _base, string memory _value)
internal
pure
returns (int) {
return _indexOf(_base, _value, 0);
}
/**
* Index Of
*
* Locates and returns the position of a character within a string starting
* from a defined offset
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string acting as the haystack to be
* searched
* @param _value The needle to search for, at present this is currently
* limited to one character
* @param _offset The starting point to start searching from which can start
* from 0, but must not exceed the length of the string
* @return int The position of the needle starting from 0 and returning -1
* in the case of no matches found
*/
function _indexOf(string memory _base, string memory _value, uint _offset)
internal
pure
returns (int) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for (uint i = _offset; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
/**
* Length
*
* Returns the length of the specified string
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string to be measured
* @return uint The length of the passed string
*/
function length(string memory _base)
internal
pure
returns (uint) {
bytes memory _baseBytes = bytes(_base);
return _baseBytes.length;
}
/**
* Sub String
*
* Extracts the beginning part of a string based on the desired length
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @return string The extracted sub string
*/
function substring(string memory _base, int _length)
internal
pure
returns (string memory) {
return _substring(_base, _length, 0);
}
/**
* Sub String
*
* Extracts the part of a string based on the desired length and offset. The
* offset and length must not exceed the lenth of the base string.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string that will be used for
* extracting the sub string from
* @param _length The length of the sub string to be extracted from the base
* @param _offset The starting point to extract the sub string from
* @return string The extracted sub string
*/
function _substring(string memory _base, int _length, int _offset)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
assert(uint(_offset + _length) <= _baseBytes.length);
string memory _tmp = new string(uint(_length));
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = uint(_offset); i < uint(_offset + _length); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
return string(_tmpBytes);
}
/**
* String Split (Very high gas cost)
*
* Splits a string into an array of strings based off the delimiter value.
* Please note this can be quite a gas expensive function due to the use of
* storage so only use if really required.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string value to be split.
* @param _value The delimiter to split the string on which must be a single
* character
* @return string[] An array of values split based off the delimiter, but
* do not container the delimiter.
*/
function split(string memory _base, string memory _value)
internal
pure
returns (string[] memory splitArr) {
bytes memory _baseBytes = bytes(_base);
uint _offset = 0;
uint _splitsCount = 1;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == -1)
break;
else {
_splitsCount++;
_offset = uint(_limit) + 1;
}
}
splitArr = new string[](_splitsCount);
_offset = 0;
_splitsCount = 0;
while (_offset < _baseBytes.length - 1) {
int _limit = _indexOf(_base, _value, _offset);
if (_limit == - 1) {
_limit = int(_baseBytes.length);
}
string memory _tmp = new string(uint(_limit) - _offset);
bytes memory _tmpBytes = bytes(_tmp);
uint j = 0;
for (uint i = _offset; i < uint(_limit); i++) {
_tmpBytes[j++] = _baseBytes[i];
}
_offset = uint(_limit) + 1;
splitArr[_splitsCount++] = string(_tmpBytes);
}
return splitArr;
}
/**
* Compare To
*
* Compares the characters of two strings, to ensure that they have an
* identical footprint
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent
*/
function compareTo(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i]) {
return false;
}
}
return true;
}
/**
* Compare To Ignore Case (High gas cost)
*
* Compares the characters of two strings, converting them to the same case
* where applicable to alphabetic characters to distinguish if the values
* match.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to compare against
* @param _value The string the base is being compared to
* @return bool Simply notates if the two string have an equivalent value
* discarding case
*/
function compareToIgnoreCase(string memory _base, string memory _value)
internal
pure
returns (bool) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
if (_baseBytes.length != _valueBytes.length) {
return false;
}
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] != _valueBytes[i] &&
_upper(_baseBytes[i]) != _upper(_valueBytes[i])) {
return false;
}
}
return true;
}
/**
* Upper
*
* Converts all the values of a string to their corresponding upper case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to upper case
* @return string
*/
function upper(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _upper(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Lower
*
* Converts all the values of a string to their corresponding lower case
* value.
*
* @param _base When being used for a data type this is the extended object
* otherwise this is the string base to convert to lower case
* @return string
*/
function lower(string memory _base)
internal
pure
returns (string memory) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
_baseBytes[i] = _lower(_baseBytes[i]);
}
return string(_baseBytes);
}
/**
* Upper
*
* Convert an alphabetic character to upper case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to upper case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a lower case otherwise returns the original value
*/
function _upper(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x61 && _b1 <= 0x7A) {
return bytes1(uint8(_b1) - 32);
}
return _b1;
}
/**
* Lower
*
* Convert an alphabetic character to lower case and return the original
* value when not alphabetic
*
* @param _b1 The byte to be converted to lower case
* @return bytes1 The converted value if the passed value was alphabetic
* and in a upper case otherwise returns the original value
*/
function _lower(bytes1 _b1)
private
pure
returns (bytes1) {
if (_b1 >= 0x41 && _b1 <= 0x5A) {
return bytes1(uint8(_b1) + 32);
}
return _b1;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PartnerFund
* @notice Where partners’ fees are managed
*/
contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable {
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using SafeMathIntLib for int256;
using Strings for string;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Partner {
bytes32 nameHash;
uint256 fee;
address wallet;
uint256 index;
bool operatorCanUpdate;
bool partnerCanUpdate;
FungibleBalanceLib.Balance active;
FungibleBalanceLib.Balance staged;
TxHistoryLib.TxHistory txHistory;
FullBalanceHistory[] fullBalanceHistory;
}
struct FullBalanceHistory {
uint256 listIndex;
int256 balance;
uint256 blockNumber;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Partner[] private partners;
mapping(bytes32 => uint256) private _indexByNameHash;
mapping(address => uint256) private _indexByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet);
event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet);
event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee);
event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee);
event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee);
event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee);
event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet);
event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet);
event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet);
event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet);
event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
_receiveEthersTo(
indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive ethers to
/// @param tag The tag of the concerned partner
function receiveEthersTo(address tag, string memory)
public
payable
{
_receiveEthersTo(
uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value)
);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Receive tokens to
/// @param tag The tag of the concerned partner
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
_receiveTokensTo(
uint256(tag) - 1, amount, currencyCt, currencyId, standard
);
}
/// @notice Hash name
/// @param name The name to be hashed
/// @return The hash value
function hashName(string memory name)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(name.upper()));
}
/// @notice Get deposit by partner and deposit indices
/// @param partnerIndex The index of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByIndices(uint256 partnerIndex, uint256 depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Require partner index is one of registered partner
require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]");
return _depositByIndices(partnerIndex - 1, depositIndex);
}
/// @notice Get deposit by partner name and deposit indices
/// @param name The name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByName(string memory name, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name is registered
return _depositByIndices(indexByName(name) - 1, depositIndex);
}
/// @notice Get deposit by partner name hash and deposit indices
/// @param nameHash The hashed name of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByNameHash(bytes32 nameHash, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner name hash is registered
return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex);
}
/// @notice Get deposit by partner wallet and deposit indices
/// @param wallet The wallet of the concerned partner
/// @param depositIndex The index of the concerned deposit
/// return The deposit parameters
function depositByWallet(address wallet, uint depositIndex)
public
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
// Implicitly require that partner wallet is registered
return _depositByIndices(indexByWallet(wallet) - 1, depositIndex);
}
/// @notice Get deposits count by partner index
/// @param index The index of the concerned partner
/// return The deposits count
function depositsCountByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]");
return _depositsCountByIndex(index - 1);
}
/// @notice Get deposits count by partner name
/// @param name The name of the concerned partner
/// return The deposits count
function depositsCountByName(string memory name)
public
view
returns (uint256)
{
// Implicitly require that partner name is registered
return _depositsCountByIndex(indexByName(name) - 1);
}
/// @notice Get deposits count by partner name hash
/// @param nameHash The hashed name of the concerned partner
/// return The deposits count
function depositsCountByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Implicitly require that partner name hash is registered
return _depositsCountByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get deposits count by partner wallet
/// @param wallet The wallet of the concerned partner
/// return The deposits count
function depositsCountByWallet(address wallet)
public
view
returns (uint256)
{
// Implicitly require that partner wallet is registered
return _depositsCountByIndex(indexByWallet(wallet) - 1);
}
/// @notice Get active balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]");
return _activeBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name hash is registered
return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get active balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The active balance
function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner index and currency
/// @param index The index of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]");
return _stagedBalanceByIndex(index - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name and currency
/// @param name The name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner name hash and currency
/// @param nameHash The hashed name of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner name is registered
return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId);
}
/// @notice Get staged balance by partner wallet and currency
/// @param wallet The wallet of the concerned partner
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// return The staged balance
function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
// Implicitly require that partner wallet is registered
return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId);
}
/// @notice Get the number of partners
/// @return The number of partners
function partnersCount()
public
view
returns (uint256)
{
return partners.length;
}
/// @notice Register a partner by name
/// @param name The name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByName(string memory name, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Require not empty name string
require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]");
// Hash name
bytes32 nameHash = hashName(name);
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameEvent(name, fee, wallet);
}
/// @notice Register a partner by name hash
/// @param nameHash The hashed name of the concerned partner
/// @param fee The partner's fee fraction
/// @param wallet The partner's wallet
/// @param partnerCanUpdate Indicator of whether partner can update fee and wallet
/// @param operatorCanUpdate Indicator of whether operator can update fee and wallet
function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
public
onlyOperator
{
// Register partner
_registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate);
// Emit event
emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet);
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
uint256 index = _indexByNameHash[nameHash];
require(0 < index, "Some error message when require fails [PartnerFund.sol:431]");
return index;
}
/// @notice Gets the 1-based index of partner by its name
/// @dev Reverts if name does not correspond to registered partner
/// @return Index of partner by given name
function indexByName(string memory name)
public
view
returns (uint256)
{
return indexByNameHash(hashName(name));
}
/// @notice Gets the 1-based index of partner by its wallet
/// @dev Reverts if wallet does not correspond to registered partner
/// @return Index of partner by given wallet
function indexByWallet(address wallet)
public
view
returns (uint256)
{
uint256 index = _indexByWallet[wallet];
require(0 < index, "Some error message when require fails [PartnerFund.sol:455]");
return index;
}
/// @notice Gauge whether a partner by the given name is registered
/// @param name The name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByName(string memory name)
public
view
returns (bool)
{
return (0 < _indexByNameHash[hashName(name)]);
}
/// @notice Gauge whether a partner by the given name hash is registered
/// @param nameHash The hashed name of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByNameHash(bytes32 nameHash)
public
view
returns (bool)
{
return (0 < _indexByNameHash[nameHash]);
}
/// @notice Gauge whether a partner by the given wallet is registered
/// @param wallet The wallet of the concerned partner
/// @return true if partner is registered, else false
function isRegisteredByWallet(address wallet)
public
view
returns (bool)
{
return (0 < _indexByWallet[wallet]);
}
/// @notice Get the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @return The fee fraction
function feeByIndex(uint256 index)
public
view
returns (uint256)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]");
return _partnerFeeByIndex(index - 1);
}
/// @notice Get the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @return The fee fraction
function feeByName(string memory name)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name is registered
return _partnerFeeByIndex(indexByName(name) - 1);
}
/// @notice Get the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The fee fraction
function feeByNameHash(bytes32 nameHash)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner name hash is registered
return _partnerFeeByIndex(indexByNameHash(nameHash) - 1);
}
/// @notice Get the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @return The fee fraction
function feeByWallet(address wallet)
public
view
returns (uint256)
{
// Get fee, implicitly requiring that partner wallet is registered
return _partnerFeeByIndex(indexByWallet(wallet) - 1);
}
/// @notice Set the partner fee fraction by the given partner index
/// @param index The index of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByIndex(uint256 index, uint256 newFee)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]");
// Update fee
uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee);
// Emit event
emit SetFeeByIndexEvent(index, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name
/// @param name The name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByName(string memory name, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee);
// Emit event
emit SetFeeByNameEvent(name, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByNameHash(bytes32 nameHash, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner name hash is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee);
// Emit event
emit SetFeeByNameHashEvent(nameHash, oldFee, newFee);
}
/// @notice Set the partner fee fraction by the given partner wallet
/// @param wallet The wallet of the concerned partner
/// @param newFee The partner's fee fraction
function setFeeByWallet(address wallet, uint256 newFee)
public
{
// Update fee, implicitly requiring that partner wallet is registered
uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee);
// Emit event
emit SetFeeByWalletEvent(wallet, oldFee, newFee);
}
/// @notice Get the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return The wallet
function walletByIndex(uint256 index)
public
view
returns (address)
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]");
return partners[index - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return The wallet
function walletByName(string memory name)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name is registered
return partners[indexByName(name) - 1].wallet;
}
/// @notice Get the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return The wallet
function walletByNameHash(bytes32 nameHash)
public
view
returns (address)
{
// Get wallet, implicitly requiring that partner name hash is registered
return partners[indexByNameHash(nameHash) - 1].wallet;
}
/// @notice Set the partner wallet by the given partner index
/// @param index The index of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByIndex(uint256 index, address newWallet)
public
{
// Require partner index is one of registered partner
require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]");
// Update wallet
address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet);
// Emit event
emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name
/// @param name The name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByName(string memory name, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet);
}
/// @notice Set the partner wallet by the given partner name hash
/// @param nameHash The hashed name of the concerned partner
/// @return newWallet The partner's wallet
function setWalletByNameHash(bytes32 nameHash, address newWallet)
public
{
// Update wallet
address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet);
// Emit event
emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet);
}
/// @notice Set the new partner wallet by the given old partner wallet
/// @param oldWallet The old wallet of the concerned partner
/// @return newWallet The partner's new wallet
function setWalletByWallet(address oldWallet, address newWallet)
public
{
// Update wallet
_setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet);
// Emit event
emit SetPartnerWalletByWalletEvent(oldWallet, newWallet);
}
/// @notice Stage the amount for subsequent withdrawal
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stage(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId));
partners[index - 1].active.sub(amount, currencyCt, currencyId);
partners[index - 1].staged.add(amount, currencyCt, currencyId);
partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index - 1].fullBalanceHistory.push(
FullBalanceHistory(
partners[index - 1].txHistory.depositsCount() - 1,
partners[index - 1].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit StageEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @notice Withdraw the given amount from staged balance
/// @param amount The concerned amount to withdraw
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Get index, implicitly requiring that msg.sender is wallet of registered partner
uint256 index = indexByWallet(msg.sender);
// Require positive amount
require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]");
// Clamp amount to move
amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId));
partners[index - 1].staged.sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:754]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
/// @dev index is 0-based
function _receiveEthersTo(uint256 index, int256 amount)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]");
// Add to active
partners[index].active.add(amount, address(0), 0);
partners[index].txHistory.addDeposit(amount, address(0), 0);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(address(0), 0),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, address(0), 0);
}
/// @dev index is 0-based
function _receiveTokensTo(uint256 index, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
private
{
// Require that index is within bounds
require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]");
require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Some error message when require fails [PartnerFund.sol:805]");
// Add to active
partners[index].active.add(amount, currencyCt, currencyId);
partners[index].txHistory.addDeposit(amount, currencyCt, currencyId);
// Add to full deposit history
partners[index].fullBalanceHistory.push(
FullBalanceHistory(
partners[index].txHistory.depositsCount() - 1,
partners[index].active.get(currencyCt, currencyId),
block.number
)
);
// Emit event
emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId);
}
/// @dev partnerIndex is 0-based
function _depositByIndices(uint256 partnerIndex, uint256 depositIndex)
private
view
returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]");
FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex];
(,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex);
balance = entry.balance;
blockNumber = entry.blockNumber;
}
/// @dev index is 0-based
function _depositsCountByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fullBalanceHistory.length;
}
/// @dev index is 0-based
function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].active.get(currencyCt, currencyId);
}
/// @dev index is 0-based
function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
return partners[index].staged.get(currencyCt, currencyId);
}
function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet,
bool partnerCanUpdate, bool operatorCanUpdate)
private
{
// Require that the name is not previously registered
require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]");
// Require possibility to update
require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]");
// Add new partner
partners.length++;
// Reference by 1-based index
uint256 index = partners.length;
// Update partner map
partners[index - 1].nameHash = nameHash;
partners[index - 1].fee = fee;
partners[index - 1].wallet = wallet;
partners[index - 1].partnerCanUpdate = partnerCanUpdate;
partners[index - 1].operatorCanUpdate = operatorCanUpdate;
partners[index - 1].index = index;
// Update name hash to index map
_indexByNameHash[nameHash] = index;
// Update wallet to index map
_indexByWallet[wallet] = index;
}
/// @dev index is 0-based
function _setPartnerFeeByIndex(uint256 index, uint256 fee)
private
returns (uint256)
{
uint256 oldFee = partners[index].fee;
// If operator tries to change verify that operator has access
if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]");
else {
// Require that msg.sender is partner
require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]");
}
// Update stored fee
partners[index].fee = fee;
return oldFee;
}
// @dev index is 0-based
function _setPartnerWalletByIndex(uint256 index, address newWallet)
private
returns (address)
{
address oldWallet = partners[index].wallet;
// If address has not been set operator is the only allowed to change it
if (oldWallet == address(0))
require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]");
// Else if operator tries to change verify that operator has access
else if (isOperator())
require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]");
else {
// Require that msg.sender is partner
require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]");
// If partner tries to change verify that partner has access
require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]");
// Require that new wallet is not zero-address if it can not be changed by operator
require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]");
}
// Update stored wallet
partners[index].wallet = newWallet;
// Update address to tag map
if (oldWallet != address(0))
_indexByWallet[oldWallet] = 0;
if (newWallet != address(0))
_indexByWallet[newWallet] = index;
return oldWallet;
}
// @dev index is 0-based
function _partnerFeeByIndex(uint256 index)
private
view
returns (uint256)
{
return partners[index].fee;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementTypesLib
* @dev Types for driip settlements
*/
library DriipSettlementTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum SettlementRole {Origin, Target}
struct SettlementParty {
uint256 nonce;
address wallet;
bool done;
uint256 doneBlockNumber;
}
struct Settlement {
string settledKind;
bytes32 settledHash;
SettlementParty origin;
SettlementParty target;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementState
* @notice Where driip settlement state is managed
*/
contract DriipSettlementState is Ownable, Servable, CommunityVotable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INIT_SETTLEMENT_ACTION = "init_settlement";
string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done";
string constant public SET_MAX_NONCE_ACTION = "set_max_nonce";
string constant public SET_FEE_TOTAL_ACTION = "set_fee_total";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
uint256 public maxDriipNonce;
DriipSettlementTypesLib.Settlement[] public settlements;
mapping(address => uint256[]) public walletSettlementIndices;
mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce;
mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap;
bool public upgradesFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
event CompleteSettlementPartyEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole,
bool done, uint256 doneBlockNumber);
event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency,
uint256 maxNonce);
event SetMaxDriipNonceEvent(uint256 maxDriipNonce);
event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce);
event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee);
event FreezeUpgradesEvent();
event UpgradeSettlementEvent(DriipSettlementTypesLib.Settlement settlement);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the count of settlements
function settlementsCount()
public
view
returns (uint256)
{
return settlements.length;
}
/// @notice Get the count of settlements for given wallet
/// @param wallet The address for which to return settlement count
/// @return count of settlements for the provided wallet
function settlementsCountByWallet(address wallet)
public
view
returns (uint256)
{
return walletSettlementIndices[wallet].length;
}
/// @notice Get settlement of given wallet and index
/// @param wallet The address for which to return settlement
/// @param index The wallet's settlement index
/// @return settlement for the provided wallet and index
function settlementByWalletAndIndex(address wallet, uint256 index)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(walletSettlementIndices[wallet].length > index, "Index out of bounds [DriipSettlementState.sol:107]");
return settlements[walletSettlementIndices[wallet][index] - 1];
}
/// @notice Get settlement of given wallet and wallet nonce
/// @param wallet The address for which to return settlement
/// @param nonce The wallet's nonce
/// @return settlement for the provided wallet and index
function settlementByWalletAndNonce(address wallet, uint256 nonce)
public
view
returns (DriipSettlementTypesLib.Settlement memory)
{
require(0 != walletNonceSettlementIndex[wallet][nonce], "No settlement found for wallet and nonce [DriipSettlementState.sol:120]");
return settlements[walletNonceSettlementIndex[wallet][nonce] - 1];
}
/// @notice Initialize settlement, i.e. create one if no such settlement exists
/// for the double pair of wallets and nonces
/// @param settledKind The kind of driip of the settlement
/// @param settledHash The hash of driip of the settlement
/// @param originWallet The address of the origin wallet
/// @param originNonce The wallet nonce of the origin wallet
/// @param targetWallet The address of the target wallet
/// @param targetNonce The wallet nonce of the target wallet
function initSettlement(string memory settledKind, bytes32 settledHash, address originWallet,
uint256 originNonce, address targetWallet, uint256 targetNonce)
public
onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION)
{
if (
0 == walletNonceSettlementIndex[originWallet][originNonce] &&
0 == walletNonceSettlementIndex[targetWallet][targetNonce]
) {
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
// Emit event
emit InitSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
}
/// @notice Set the done of the given settlement role in the given settlement
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @param done The done flag
function completeSettlementParty(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole, bool done)
public
onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:181]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage party =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin :
settlements[index - 1].target;
// Update party done and done block number properties
party.done = done;
party.doneBlockNumber = done ? block.number : 0;
// Emit event
emit CompleteSettlementPartyEvent(wallet, nonce, settlementRole, done, party.doneBlockNumber);
}
/// @notice Gauge whether the settlement is done wrt the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Return done
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.done :
settlements[index - 1].target.done
);
}
/// @notice Gauge whether the settlement is done wrt the given wallet, nonce
/// and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return True if settlement is done for role, else false
function isSettlementPartyDone(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (bool)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Return false if settlement does not exist
if (0 == index)
return false;
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:246]");
// Return done
return settlementParty.done;
}
/// @notice Get the done block number of the settlement party with the given wallet and nonce
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:265]");
// Return done block number
return (
wallet == settlements[index - 1].origin.wallet ?
settlements[index - 1].origin.doneBlockNumber :
settlements[index - 1].target.doneBlockNumber
);
}
/// @notice Get the done block number of the settlement party with the given wallet, nonce and settlement role
/// @param wallet The address of the concerned wallet
/// @param nonce The nonce of the concerned wallet
/// @param settlementRole The settlement role
/// @return The done block number of the settlement wrt the given settlement role
function settlementPartyDoneBlockNumber(address wallet, uint256 nonce,
DriipSettlementTypesLib.SettlementRole settlementRole)
public
view
returns (uint256)
{
// Get the 1-based index of the settlement
uint256 index = walletNonceSettlementIndex[wallet][nonce];
// Require the existence of settlement
require(0 != index, "No settlement found for wallet and nonce [DriipSettlementState.sol:290]");
// Get the settlement party
DriipSettlementTypesLib.SettlementParty storage settlementParty =
DriipSettlementTypesLib.SettlementRole.Origin == settlementRole ?
settlements[index - 1].origin : settlements[index - 1].target;
// Require that wallet is party of the right role
require(wallet == settlementParty.wallet, "Wallet has wrong settlement role [DriipSettlementState.sol:298]");
// Return done block number
return settlementParty.doneBlockNumber;
}
/// @notice Set the max (driip) nonce
/// @param _maxDriipNonce The max nonce
function setMaxDriipNonce(uint256 _maxDriipNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
maxDriipNonce = _maxDriipNonce;
// Emit event
emit SetMaxDriipNonceEvent(maxDriipNonce);
}
/// @notice Update the max driip nonce property from CommunityVote contract
function updateMaxDriipNonceFromCommunityVote()
public
{
uint256 _maxDriipNonce = communityVote.getMaxDriipNonce();
if (0 == _maxDriipNonce)
return;
maxDriipNonce = _maxDriipNonce;
// Emit event
emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce);
}
/// @notice Get the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The max nonce
function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
return walletCurrencyMaxNonce[wallet][currency.ct][currency.id];
}
/// @notice Set the max nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @param maxNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency memory currency,
uint256 maxNonce)
public
onlyEnabledServiceAction(SET_MAX_NONCE_ACTION)
{
// Update max nonce value
walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce;
// Emit event
emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce);
}
/// @notice Get the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param currency The concerned currency
/// @return The total fee
function totalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency)
public
view
returns (MonetaryTypesLib.NoncedAmount memory)
{
return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id];
}
/// @notice Set the total fee payed by the given wallet to the given beneficiary and destination
/// in the given currency
/// @param wallet The address of the concerned wallet
/// @param beneficiary The concerned beneficiary
/// @param destination The concerned destination
/// @param _totalFee The total fee
function setTotalFee(address wallet, Beneficiary beneficiary, address destination,
MonetaryTypesLib.Currency memory currency, MonetaryTypesLib.NoncedAmount memory _totalFee)
public
onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION)
{
// Update total fees value
totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee;
// Emit event
emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee);
}
/// @notice Freeze all future settlement upgrades
/// @dev This operation can not be undone
function freezeUpgrades()
public
onlyDeployer
{
// Freeze upgrade
upgradesFrozen = true;
// Emit event
emit FreezeUpgradesEvent();
}
/// @notice Upgrade settlement from other driip settlement state instance
function upgradeSettlement(string memory settledKind, bytes32 settledHash,
address originWallet, uint256 originNonce, bool originDone, uint256 originDoneBlockNumber,
address targetWallet, uint256 targetNonce, bool targetDone, uint256 targetDoneBlockNumber)
public
onlyDeployer
{
// Require that upgrades have not been frozen
require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]");
// Require that settlement has not been initialized/upgraded already
require(0 == walletNonceSettlementIndex[originWallet][originNonce], "Settlement exists for origin wallet and nonce [DriipSettlementState.sol:416]");
require(0 == walletNonceSettlementIndex[targetWallet][targetNonce], "Settlement exists for target wallet and nonce [DriipSettlementState.sol:417]");
// Create new settlement
settlements.length++;
// Get the 0-based index
uint256 index = settlements.length - 1;
// Update settlement
settlements[index].settledKind = settledKind;
settlements[index].settledHash = settledHash;
settlements[index].origin.nonce = originNonce;
settlements[index].origin.wallet = originWallet;
settlements[index].origin.done = originDone;
settlements[index].origin.doneBlockNumber = originDoneBlockNumber;
settlements[index].target.nonce = targetNonce;
settlements[index].target.wallet = targetWallet;
settlements[index].target.done = targetDone;
settlements[index].target.doneBlockNumber = targetDoneBlockNumber;
// Emit event
emit UpgradeSettlementEvent(settlements[index]);
// Store 1-based index value
index++;
walletSettlementIndices[originWallet].push(index);
walletSettlementIndices[targetWallet].push(index);
walletNonceSettlementIndex[originWallet][originNonce] = index;
walletNonceSettlementIndex[targetWallet][targetNonce] = index;
}
} | * Concat (High gas cost) Appends two strings together and returns a new value @param _base When being used for a data type this is the extended object otherwise this is the string which will be the concatenated prefix @param _value The value to be the concatenated suffix @return string The resulting string from combinging the base and value/ | returns (string memory) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length > 0);
string memory _tmpValue = new string(_baseBytes.length +
_valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for (i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for (i = 0; i < _valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
| 1,005,993 | [
1,
15113,
261,
8573,
16189,
6991,
13,
6181,
87,
2795,
2064,
9475,
471,
1135,
279,
394,
460,
225,
389,
1969,
5203,
3832,
1399,
364,
279,
501,
618,
333,
353,
326,
7021,
733,
2868,
3541,
333,
353,
326,
533,
1492,
903,
506,
326,
22080,
2868,
1633,
225,
389,
1132,
1021,
460,
358,
506,
326,
22080,
3758,
327,
533,
1021,
8156,
533,
628,
3894,
310,
310,
326,
1026,
471,
460,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
1731,
3778,
389,
1969,
2160,
273,
1731,
24899,
1969,
1769,
203,
3639,
1731,
3778,
389,
1132,
2160,
273,
1731,
24899,
1132,
1769,
203,
203,
3639,
1815,
24899,
1132,
2160,
18,
2469,
405,
374,
1769,
203,
203,
3639,
533,
3778,
389,
5645,
620,
273,
394,
533,
24899,
1969,
2160,
18,
2469,
397,
203,
5411,
389,
1132,
2160,
18,
2469,
1769,
203,
3639,
1731,
3778,
389,
2704,
620,
273,
1731,
24899,
5645,
620,
1769,
203,
203,
3639,
2254,
277,
31,
203,
3639,
2254,
525,
31,
203,
203,
3639,
364,
261,
77,
273,
374,
31,
277,
411,
389,
1969,
2160,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
2704,
620,
63,
78,
9904,
65,
273,
389,
1969,
2160,
63,
77,
15533,
203,
3639,
289,
203,
203,
3639,
364,
261,
77,
273,
374,
31,
277,
411,
389,
1132,
2160,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
2704,
620,
63,
78,
9904,
65,
273,
389,
1132,
2160,
63,
77,
15533,
203,
3639,
289,
203,
203,
3639,
327,
533,
24899,
2704,
620,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
import "./BaseJumpRateModelV2.sol";
import "./InterestRateModel.sol";
/**
* @title rLending's JumpRateModel Contract V2 for V2 cTokens
* @author rLending
* @notice Supports only for V2 cTokens
*/
contract JumpRateModelV2 is InterestRateModel, BaseJumpRateModelV2 {
/**
* @notice Calculates the current borrow rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint) {
return getBorrowRateInternal(cash, borrows, reserves);
}
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_)
BaseJumpRateModelV2(baseRatePerYear,multiplierPerYear,jumpMultiplierPerYear,kink_,owner_) public {}
}
| * @title rLending's JumpRateModel Contract V2 for V2 cTokens @author rLending @notice Supports only for V2 cTokens/ | contract JumpRateModelV2 is InterestRateModel, BaseJumpRateModelV2 {
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint) {
return getBorrowRateInternal(cash, borrows, reserves);
}
constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_)
BaseJumpRateModelV2(baseRatePerYear,multiplierPerYear,jumpMultiplierPerYear,kink_,owner_) public {}
}
| 2,538,481 | [
1,
86,
48,
2846,
1807,
804,
2801,
4727,
1488,
13456,
776,
22,
364,
776,
22,
276,
5157,
225,
436,
48,
2846,
225,
25110,
1338,
364,
776,
22,
276,
5157,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
804,
2801,
4727,
1488,
58,
22,
353,
5294,
395,
4727,
1488,
16,
3360,
26743,
4727,
1488,
58,
22,
225,
288,
203,
203,
565,
445,
2882,
15318,
4727,
12,
11890,
276,
961,
16,
2254,
324,
280,
3870,
16,
2254,
400,
264,
3324,
13,
3903,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
327,
2882,
15318,
4727,
3061,
12,
71,
961,
16,
324,
280,
3870,
16,
400,
264,
3324,
1769,
203,
565,
289,
203,
203,
565,
3885,
12,
11890,
1026,
4727,
2173,
5593,
16,
2254,
15027,
2173,
5593,
16,
2254,
11833,
23365,
2173,
5593,
16,
2254,
417,
754,
67,
16,
1758,
3410,
67,
13,
203,
377,
202,
2171,
26743,
4727,
1488,
58,
22,
12,
1969,
4727,
2173,
5593,
16,
20538,
2173,
5593,
16,
24574,
23365,
2173,
5593,
16,
79,
754,
67,
16,
8443,
67,
13,
1071,
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
] |
pragma solidity ^0.4.11;
contract PullPayInterface {
function asyncSend(address _dest) public payable;
}
contract Governable {
// list of admins, council at first spot
address[] public admins;
function Governable() {
admins.length = 1;
admins[0] = msg.sender;
}
modifier onlyAdmins() {
bool isAdmin = false;
for (uint256 i = 0; i < admins.length; i++) {
if (msg.sender == admins[i]) {
isAdmin = true;
}
}
require(isAdmin == true);
_;
}
function addAdmin(address _admin) public onlyAdmins {
for (uint256 i = 0; i < admins.length; i++) {
require(_admin != admins[i]);
}
require(admins.length < 10);
admins[admins.length++] = _admin;
}
function removeAdmin(address _admin) public onlyAdmins {
uint256 pos = admins.length;
for (uint256 i = 0; i < admins.length; i++) {
if (_admin == admins[i]) {
pos = i;
}
}
require(pos < admins.length);
// if not last element, switch with last
if (pos < admins.length - 1) {
admins[pos] = admins[admins.length - 1];
}
// then cut off the tail
admins.length--;
}
}
contract StorageEnabled {
// satelite contract addresses
address public storageAddr;
function StorageEnabled(address _storageAddr) {
storageAddr = _storageAddr;
}
// ############################################
// ########### NUTZ FUNCTIONS ################
// ############################################
// all Nutz balances
function babzBalanceOf(address _owner) constant returns (uint256) {
return Storage(storageAddr).getBal('Nutz', _owner);
}
function _setBabzBalanceOf(address _owner, uint256 _newValue) internal {
Storage(storageAddr).setBal('Nutz', _owner, _newValue);
}
// active supply - sum of balances above
function activeSupply() constant returns (uint256) {
return Storage(storageAddr).getUInt('Nutz', 'activeSupply');
}
function _setActiveSupply(uint256 _newActiveSupply) internal {
Storage(storageAddr).setUInt('Nutz', 'activeSupply', _newActiveSupply);
}
// burn pool - inactive supply
function burnPool() constant returns (uint256) {
return Storage(storageAddr).getUInt('Nutz', 'burnPool');
}
function _setBurnPool(uint256 _newBurnPool) internal {
Storage(storageAddr).setUInt('Nutz', 'burnPool', _newBurnPool);
}
// power pool - inactive supply
function powerPool() constant returns (uint256) {
return Storage(storageAddr).getUInt('Nutz', 'powerPool');
}
function _setPowerPool(uint256 _newPowerPool) internal {
Storage(storageAddr).setUInt('Nutz', 'powerPool', _newPowerPool);
}
// ############################################
// ########### POWER FUNCTIONS #############
// ############################################
// all power balances
function powerBalanceOf(address _owner) constant returns (uint256) {
return Storage(storageAddr).getBal('Power', _owner);
}
function _setPowerBalanceOf(address _owner, uint256 _newValue) internal {
Storage(storageAddr).setBal('Power', _owner, _newValue);
}
function outstandingPower() constant returns (uint256) {
return Storage(storageAddr).getUInt('Power', 'outstandingPower');
}
function _setOutstandingPower(uint256 _newOutstandingPower) internal {
Storage(storageAddr).setUInt('Power', 'outstandingPower', _newOutstandingPower);
}
function authorizedPower() constant returns (uint256) {
return Storage(storageAddr).getUInt('Power', 'authorizedPower');
}
function _setAuthorizedPower(uint256 _newAuthorizedPower) internal {
Storage(storageAddr).setUInt('Power', 'authorizedPower', _newAuthorizedPower);
}
function downs(address _user) constant public returns (uint256 total, uint256 left, uint256 start) {
uint256 rawBytes = Storage(storageAddr).getBal('PowerDown', _user);
start = uint64(rawBytes);
left = uint96(rawBytes >> (64));
total = uint96(rawBytes >> (96 + 64));
return;
}
function _setDownRequest(address _holder, uint256 total, uint256 left, uint256 start) internal {
uint256 result = uint64(start) + (left << 64) + (total << (96 + 64));
Storage(storageAddr).setBal('PowerDown', _holder, result);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Governable {
bool public paused = true;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyAdmins whenNotPaused {
paused = true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyAdmins whenPaused {
//TODO: do some checks
paused = false;
}
}
/*
* ERC20Basic
* Simpler version of ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
function totalSupply() constant returns (uint256);
function balanceOf(address _owner) constant returns (uint256);
function transfer(address _to, uint256 _value) returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) returns (bool);
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC223Basic {
// active supply of tokens
function activeSupply() constant returns (uint256);
function allowance(address _owner, address _spender) constant returns (uint256);
function transferFrom(address _from, address _to, uint _value) returns (bool);
function approve(address _spender, uint256 _value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
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 {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Power is Ownable, ERC20Basic {
event Slashing(address indexed holder, uint value, bytes32 data);
string public name = "Acebusters Power";
string public symbol = "ABP";
uint256 public decimals = 12;
function balanceOf(address _holder) constant returns (uint256) {
return ControllerInterface(owner).powerBalanceOf(_holder);
}
function totalSupply() constant returns (uint256) {
return ControllerInterface(owner).powerTotalSupply();
}
function activeSupply() constant returns (uint256) {
return ControllerInterface(owner).outstandingPower();
}
// ############################################
// ########### ADMIN FUNCTIONS ################
// ############################################
function slashPower(address _holder, uint256 _value, bytes32 _data) public onlyOwner {
Slashing(_holder, _value, _data);
}
function powerUp(address _holder, uint256 _value) public onlyOwner {
// NTZ transfered from user's balance to power pool
Transfer(address(0), _holder, _value);
}
// ############################################
// ########### PUBLIC FUNCTIONS ###############
// ############################################
// registers a powerdown request
function transfer(address _to, uint256 _amountPower) public returns (bool success) {
// make Power not transferable
require(_to == address(0));
ControllerInterface(owner).createDownRequest(msg.sender, _amountPower);
Transfer(msg.sender, address(0), _amountPower);
return true;
}
function downtime() public returns (uint256) {
ControllerInterface(owner).downtime;
}
function downTick(address _owner) public {
ControllerInterface(owner).downTick(_owner, now);
}
function downs(address _owner) constant public returns (uint256, uint256, uint256) {
return ControllerInterface(owner).downs(_owner);
}
}
contract Storage is Ownable {
struct Crate {
mapping(bytes32 => uint256) uints;
mapping(bytes32 => address) addresses;
mapping(bytes32 => bool) bools;
mapping(address => uint256) bals;
}
mapping(bytes32 => Crate) crates;
function setUInt(bytes32 _crate, bytes32 _key, uint256 _value) onlyOwner {
crates[_crate].uints[_key] = _value;
}
function getUInt(bytes32 _crate, bytes32 _key) constant returns(uint256) {
return crates[_crate].uints[_key];
}
function setAddress(bytes32 _crate, bytes32 _key, address _value) onlyOwner {
crates[_crate].addresses[_key] = _value;
}
function getAddress(bytes32 _crate, bytes32 _key) constant returns(address) {
return crates[_crate].addresses[_key];
}
function setBool(bytes32 _crate, bytes32 _key, bool _value) onlyOwner {
crates[_crate].bools[_key] = _value;
}
function getBool(bytes32 _crate, bytes32 _key) constant returns(bool) {
return crates[_crate].bools[_key];
}
function setBal(bytes32 _crate, address _key, uint256 _value) onlyOwner {
crates[_crate].bals[_key] = _value;
}
function getBal(bytes32 _crate, address _key) constant returns(uint256) {
return crates[_crate].bals[_key];
}
}
contract NutzEnabled is Pausable, StorageEnabled {
using SafeMath for uint;
// satelite contract addresses
address public nutzAddr;
modifier onlyNutz() {
require(msg.sender == nutzAddr);
_;
}
function NutzEnabled(address _nutzAddr, address _storageAddr)
StorageEnabled(_storageAddr) {
nutzAddr = _nutzAddr;
}
// ############################################
// ########### NUTZ FUNCTIONS ################
// ############################################
// total supply(modified for etherscan display)
function totalSupply() constant returns (uint256) {
return activeSupply();
}
// total supply(for internal calculations)
function completeSupply() constant returns (uint256) {
return activeSupply().add(powerPool()).add(burnPool());
}
// allowances according to ERC20
// not written to storage, as not very critical
mapping (address => mapping (address => uint)) internal allowed;
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
function approve(address _owner, address _spender, uint256 _amountBabz) public onlyNutz whenNotPaused {
require(_owner != _spender);
allowed[_owner][_spender] = _amountBabz;
}
function _transfer(address _from, address _to, uint256 _amountBabz, bytes _data) internal {
require(_to != address(this));
require(_to != address(0));
require(_amountBabz > 0);
require(_from != _to);
_setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz));
_setBabzBalanceOf(_to, babzBalanceOf(_to).add(_amountBabz));
}
function transfer(address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused {
_transfer(_from, _to, _amountBabz, _data);
}
function transferFrom(address _sender, address _from, address _to, uint256 _amountBabz, bytes _data) public onlyNutz whenNotPaused {
allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz);
_transfer(_from, _to, _amountBabz, _data);
}
}
/*
* Contract that is working with ERC223 tokens
*/
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data);
}
contract ControllerInterface {
// State Variables
bool public paused;
address public nutzAddr;
// Nutz functions
function babzBalanceOf(address _owner) constant returns (uint256);
function activeSupply() constant returns (uint256);
function burnPool() constant returns (uint256);
function powerPool() constant returns (uint256);
function totalSupply() constant returns (uint256);
function completeSupply() constant returns (uint256);
function allowance(address _owner, address _spender) constant returns (uint256);
function approve(address _owner, address _spender, uint256 _amountBabz) public;
function transfer(address _from, address _to, uint256 _amountBabz, bytes _data) public;
function transferFrom(address _sender, address _from, address _to, uint256 _amountBabz, bytes _data) public;
// Market functions
function floor() constant returns (uint256);
function ceiling() constant returns (uint256);
function purchase(address _sender, uint256 _value, uint256 _price) public returns (uint256);
function sell(address _from, uint256 _price, uint256 _amountBabz);
// Power functions
function powerBalanceOf(address _owner) constant returns (uint256);
function outstandingPower() constant returns (uint256);
function authorizedPower() constant returns (uint256);
function powerTotalSupply() constant returns (uint256);
function powerUp(address _sender, address _from, uint256 _amountBabz) public;
function downTick(address _owner, uint256 _now) public;
function createDownRequest(address _owner, uint256 _amountPower) public;
function downs(address _owner) constant public returns(uint256, uint256, uint256);
function downtime() constant returns (uint256);
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments.
*/
contract PullPayment is Ownable {
using SafeMath for uint256;
uint public dailyLimit = 1000000000000000000000; // 1 ETH
uint public lastDay;
uint public spentToday;
// 8bytes date, 24 bytes value
mapping(address => uint256) internal payments;
modifier onlyNutz() {
require(msg.sender == ControllerInterface(owner).nutzAddr());
_;
}
modifier whenNotPaused () {
require(!ControllerInterface(owner).paused());
_;
}
function balanceOf(address _owner) constant returns (uint256 value) {
return uint192(payments[_owner]);
}
function paymentOf(address _owner) constant returns (uint256 value, uint256 date) {
value = uint192(payments[_owner]);
date = (payments[_owner] >> 192);
return;
}
/// @dev Allows to change the daily limit. Transaction has to be sent by wallet.
/// @param _dailyLimit Amount in wei.
function changeDailyLimit(uint _dailyLimit) public onlyOwner {
dailyLimit = _dailyLimit;
}
function changeWithdrawalDate(address _owner, uint256 _newDate) public onlyOwner {
// allow to withdraw immediately
// move witdrawal date more days into future
payments[_owner] = (_newDate << 192) + uint192(payments[_owner]);
}
function asyncSend(address _dest) public payable onlyNutz {
require(msg.value > 0);
uint256 newValue = msg.value.add(uint192(payments[_dest]));
uint256 newDate;
if (isUnderLimit(msg.value)) {
uint256 date = payments[_dest] >> 192;
newDate = (date > now) ? date : now;
} else {
newDate = now.add(3 days);
}
spentToday = spentToday.add(msg.value);
payments[_dest] = (newDate << 192) + uint192(newValue);
}
function withdraw() public whenNotPaused {
address untrustedRecipient = msg.sender;
uint256 amountWei = uint192(payments[untrustedRecipient]);
require(amountWei != 0);
require(now >= (payments[untrustedRecipient] >> 192));
require(this.balance >= amountWei);
payments[untrustedRecipient] = 0;
assert(untrustedRecipient.call.gas(1000).value(amountWei)());
}
/*
* Internal functions
*/
/// @dev Returns if amount is within daily limit and resets spentToday after one day.
/// @param amount Amount to withdraw.
/// @return Returns if amount is under daily limit.
function isUnderLimit(uint amount) internal returns (bool) {
if (now > lastDay.add(24 hours)) {
lastDay = now;
spentToday = 0;
}
// not using safe math because we don't want to throw;
if (spentToday + amount > dailyLimit || spentToday + amount < spentToday) {
return false;
}
return true;
}
}
/**
* Nutz implements a price floor and a price ceiling on the token being
* sold. It is based of the zeppelin token contract.
*/
contract Nutz is Ownable, ERC20 {
event Sell(address indexed seller, uint256 value);
string public name = "Acebusters Nutz";
// acebusters units:
// 10^12 - Nutz (NTZ)
// 10^9 - Jonyz
// 10^6 - Helcz
// 10^3 - Pascalz
// 10^0 - Babz
string public symbol = "NTZ";
uint256 public decimals = 12;
// returns balances of active holders
function balanceOf(address _owner) constant returns (uint) {
return ControllerInterface(owner).babzBalanceOf(_owner);
}
function totalSupply() constant returns (uint256) {
return ControllerInterface(owner).totalSupply();
}
function activeSupply() constant returns (uint256) {
return ControllerInterface(owner).activeSupply();
}
// return remaining allowance
// if calling return allowed[address(this)][_spender];
// returns balance of ether parked to be withdrawn
function allowance(address _owner, address _spender) constant returns (uint256) {
return ControllerInterface(owner).allowance(_owner, _spender);
}
// returns either the salePrice, or if reserve does not suffice
// for active supply, returns maxFloor
function floor() constant returns (uint256) {
return ControllerInterface(owner).floor();
}
// returns either the salePrice, or if reserve does not suffice
// for active supply, returns maxFloor
function ceiling() constant returns (uint256) {
return ControllerInterface(owner).ceiling();
}
function powerPool() constant returns (uint256) {
return ControllerInterface(owner).powerPool();
}
function _checkDestination(address _from, address _to, uint256 _value, bytes _data) internal {
// erc223: Retrieve the size of the code on target address, this needs assembly .
uint256 codeLength;
assembly {
codeLength := extcodesize(_to)
}
if(codeLength>0) {
ERC223ReceivingContract untrustedReceiver = ERC223ReceivingContract(_to);
// untrusted contract call
untrustedReceiver.tokenFallback(_from, _value, _data);
}
}
// ############################################
// ########### ADMIN FUNCTIONS ################
// ############################################
function powerDown(address powerAddr, address _holder, uint256 _amountBabz) public onlyOwner {
bytes memory empty;
_checkDestination(powerAddr, _holder, _amountBabz, empty);
// NTZ transfered from power pool to user's balance
Transfer(powerAddr, _holder, _amountBabz);
}
function asyncSend(address _pullAddr, address _dest, uint256 _amountWei) public onlyOwner {
assert(_amountWei <= this.balance);
PullPayInterface(_pullAddr).asyncSend.value(_amountWei)(_dest);
}
// ############################################
// ########### PUBLIC FUNCTIONS ###############
// ############################################
function approve(address _spender, uint256 _amountBabz) public {
ControllerInterface(owner).approve(msg.sender, _spender, _amountBabz);
Approval(msg.sender, _spender, _amountBabz);
}
function transfer(address _to, uint256 _amountBabz, bytes _data) public returns (bool) {
ControllerInterface(owner).transfer(msg.sender, _to, _amountBabz, _data);
Transfer(msg.sender, _to, _amountBabz);
_checkDestination(msg.sender, _to, _amountBabz, _data);
return true;
}
function transfer(address _to, uint256 _amountBabz) public returns (bool) {
bytes memory empty;
return transfer(_to, _amountBabz, empty);
}
function transData(address _to, uint256 _amountBabz, bytes _data) public returns (bool) {
return transfer(_to, _amountBabz, _data);
}
function transferFrom(address _from, address _to, uint256 _amountBabz, bytes _data) public returns (bool) {
ControllerInterface(owner).transferFrom(msg.sender, _from, _to, _amountBabz, _data);
Transfer(_from, _to, _amountBabz);
_checkDestination(_from, _to, _amountBabz, _data);
return true;
}
function transferFrom(address _from, address _to, uint256 _amountBabz) public returns (bool) {
bytes memory empty;
return transferFrom(_from, _to, _amountBabz, empty);
}
function () public payable {
uint256 price = ControllerInterface(owner).ceiling();
purchase(price);
require(msg.value > 0);
}
function purchase(uint256 _price) public payable {
require(msg.value > 0);
uint256 amountBabz = ControllerInterface(owner).purchase(msg.sender, msg.value, _price);
Transfer(owner, msg.sender, amountBabz);
bytes memory empty;
_checkDestination(address(this), msg.sender, amountBabz, empty);
}
function sell(uint256 _price, uint256 _amountBabz) public {
require(_amountBabz != 0);
ControllerInterface(owner).sell(msg.sender, _price, _amountBabz);
Sell(msg.sender, _amountBabz);
}
function powerUp(uint256 _amountBabz) public {
Transfer(msg.sender, owner, _amountBabz);
ControllerInterface(owner).powerUp(msg.sender, msg.sender, _amountBabz);
}
}
contract MarketEnabled is NutzEnabled {
uint256 constant INFINITY = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// address of the pull payemnt satelite
address public pullAddr;
// the Token sale mechanism parameters:
// purchasePrice is the number of NTZ received for purchase with 1 ETH
uint256 internal purchasePrice;
// floor is the number of NTZ needed, to receive 1 ETH in sell
uint256 internal salePrice;
function MarketEnabled(address _pullAddr, address _storageAddr, address _nutzAddr)
NutzEnabled(_nutzAddr, _storageAddr) {
pullAddr = _pullAddr;
}
function ceiling() constant returns (uint256) {
return purchasePrice;
}
// returns either the salePrice, or if reserve does not suffice
// for active supply, returns maxFloor
function floor() constant returns (uint256) {
if (nutzAddr.balance == 0) {
return INFINITY;
}
uint256 maxFloor = activeSupply().mul(1000000).div(nutzAddr.balance); // 1,000,000 WEI, used as price factor
// return max of maxFloor or salePrice
return maxFloor >= salePrice ? maxFloor : salePrice;
}
function moveCeiling(uint256 _newPurchasePrice) public onlyAdmins {
require(_newPurchasePrice <= salePrice);
purchasePrice = _newPurchasePrice;
}
function moveFloor(uint256 _newSalePrice) public onlyAdmins {
require(_newSalePrice >= purchasePrice);
// moveFloor fails if the administrator tries to push the floor so low
// that the sale mechanism is no longer able to buy back all tokens at
// the floor price if those funds were to be withdrawn.
if (_newSalePrice < INFINITY) {
require(nutzAddr.balance >= activeSupply().mul(1000000).div(_newSalePrice)); // 1,000,000 WEI, used as price factor
}
salePrice = _newSalePrice;
}
function purchase(address _sender, uint256 _value, uint256 _price) public onlyNutz whenNotPaused returns (uint256) {
// disable purchases if purchasePrice set to 0
require(purchasePrice > 0);
require(_price == purchasePrice);
uint256 amountBabz = purchasePrice.mul(_value).div(1000000); // 1,000,000 WEI, used as price factor
// avoid deposits that issue nothing
// might happen with very high purchase price
require(amountBabz > 0);
// make sure power pool grows proportional to economy
uint256 activeSup = activeSupply();
uint256 powPool = powerPool();
if (powPool > 0) {
uint256 powerShare = powPool.mul(amountBabz).div(activeSup.add(burnPool()));
_setPowerPool(powPool.add(powerShare));
}
_setActiveSupply(activeSup.add(amountBabz));
_setBabzBalanceOf(_sender, babzBalanceOf(_sender).add(amountBabz));
return amountBabz;
}
function sell(address _from, uint256 _price, uint256 _amountBabz) public onlyNutz whenNotPaused {
uint256 effectiveFloor = floor();
require(_amountBabz != 0);
require(effectiveFloor != INFINITY);
require(_price == effectiveFloor);
uint256 amountWei = _amountBabz.mul(1000000).div(effectiveFloor); // 1,000,000 WEI, used as price factor
require(amountWei > 0);
// make sure power pool shrinks proportional to economy
uint256 powPool = powerPool();
uint256 activeSup = activeSupply();
if (powPool > 0) {
uint256 powerShare = powPool.mul(_amountBabz).div(activeSup.add(burnPool()));
_setPowerPool(powPool.sub(powerShare));
}
_setActiveSupply(activeSup.sub(_amountBabz));
_setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz));
Nutz(nutzAddr).asyncSend(pullAddr, _from, amountWei);
}
// withdraw excessive reserve - i.e. milestones
function allocateEther(uint256 _amountWei, address _beneficiary) public onlyAdmins {
require(_amountWei > 0);
// allocateEther fails if allocating those funds would mean that the
// sale mechanism is no longer able to buy back all tokens at the floor
// price if those funds were to be withdrawn.
require(nutzAddr.balance.sub(_amountWei) >= activeSupply().mul(1000000).div(salePrice)); // 1,000,000 WEI, used as price factor
Nutz(nutzAddr).asyncSend(pullAddr, _beneficiary, _amountWei);
}
}
contract PowerEnabled is MarketEnabled {
// satelite contract addresses
address public powerAddr;
// maxPower is a limit of total power that can be outstanding
// maxPower has a valid value between outstandingPower and authorizedPow/2
uint256 public maxPower = 0;
// time it should take to power down
uint256 public downtime;
uint public constant MIN_SHARE_OF_POWER = 100000;
modifier onlyPower() {
require(msg.sender == powerAddr);
_;
}
function PowerEnabled(address _powerAddr, address _pullAddr, address _storageAddr, address _nutzAddr)
MarketEnabled(_pullAddr, _nutzAddr, _storageAddr) {
powerAddr = _powerAddr;
}
function setMaxPower(uint256 _maxPower) public onlyAdmins {
require(outstandingPower() <= _maxPower && _maxPower < authorizedPower());
maxPower = _maxPower;
}
function setDowntime(uint256 _downtime) public onlyAdmins {
downtime = _downtime;
}
function minimumPowerUpSizeBabz() public constant returns (uint256) {
uint256 completeSupplyBabz = completeSupply();
if (completeSupplyBabz == 0) {
return INFINITY;
}
return completeSupplyBabz.div(MIN_SHARE_OF_POWER);
}
// this is called when NTZ are deposited into the burn pool
function dilutePower(uint256 _amountBabz, uint256 _amountPower) public onlyAdmins {
uint256 authorizedPow = authorizedPower();
uint256 totalBabz = completeSupply();
if (authorizedPow == 0) {
// during the first capital increase, set value directly as authorized shares
_setAuthorizedPower((_amountPower > 0) ? _amountPower : _amountBabz.add(totalBabz));
} else {
// in later increases, expand authorized shares at same rate like economy
_setAuthorizedPower(authorizedPow.mul(totalBabz.add(_amountBabz)).div(totalBabz));
}
_setBurnPool(burnPool().add(_amountBabz));
}
function _slashPower(address _holder, uint256 _value, bytes32 _data) internal {
uint256 previouslyOutstanding = outstandingPower();
_setOutstandingPower(previouslyOutstanding.sub(_value));
// adjust size of power pool
uint256 powPool = powerPool();
uint256 slashingBabz = _value.mul(powPool).div(previouslyOutstanding);
_setPowerPool(powPool.sub(slashingBabz));
// put event into satelite contract
Power(powerAddr).slashPower(_holder, _value, _data);
}
function slashPower(address _holder, uint256 _value, bytes32 _data) public onlyAdmins {
_setPowerBalanceOf(_holder, powerBalanceOf(_holder).sub(_value));
_slashPower(_holder, _value, _data);
}
function slashDownRequest(uint256 _pos, address _holder, uint256 _value, bytes32 _data) public onlyAdmins {
var (total, left, start) = downs(_holder);
left = left.sub(_value);
_setDownRequest(_holder, total, left, start);
_slashPower(_holder, _value, _data);
}
// this is called when NTZ are deposited into the power pool
function powerUp(address _sender, address _from, uint256 _amountBabz) public onlyNutz whenNotPaused {
uint256 authorizedPow = authorizedPower();
require(authorizedPow != 0);
require(_amountBabz != 0);
uint256 totalBabz = completeSupply();
require(totalBabz != 0);
uint256 amountPow = _amountBabz.mul(authorizedPow).div(totalBabz);
// check pow limits
uint256 outstandingPow = outstandingPower();
require(outstandingPow.add(amountPow) <= maxPower);
uint256 powBal = powerBalanceOf(_from).add(amountPow);
require(powBal >= authorizedPow.div(MIN_SHARE_OF_POWER));
if (_sender != _from) {
allowed[_from][_sender] = allowed[_from][_sender].sub(_amountBabz);
}
_setOutstandingPower(outstandingPow.add(amountPow));
_setPowerBalanceOf(_from, powBal);
_setActiveSupply(activeSupply().sub(_amountBabz));
_setBabzBalanceOf(_from, babzBalanceOf(_from).sub(_amountBabz));
_setPowerPool(powerPool().add(_amountBabz));
Power(powerAddr).powerUp(_from, amountPow);
}
function powerTotalSupply() constant returns (uint256) {
uint256 issuedPower = authorizedPower().div(2);
// return max of maxPower or issuedPower
return maxPower >= issuedPower ? maxPower : issuedPower;
}
function _vestedDown(uint256 _total, uint256 _left, uint256 _start, uint256 _now) internal constant returns (uint256) {
if (_now <= _start) {
return 0;
}
// calculate amountVested
// amountVested is amount that can be withdrawn according to time passed
uint256 timePassed = _now.sub(_start);
if (timePassed > downtime) {
timePassed = downtime;
}
uint256 amountVested = _total.mul(timePassed).div(downtime);
uint256 amountFrozen = _total.sub(amountVested);
if (_left <= amountFrozen) {
return 0;
}
return _left.sub(amountFrozen);
}
function createDownRequest(address _owner, uint256 _amountPower) public onlyPower whenNotPaused {
// prevent powering down tiny amounts
// when powering down, at least completeSupply/minShare Power should be claimed
require(_amountPower >= authorizedPower().div(MIN_SHARE_OF_POWER));
_setPowerBalanceOf(_owner, powerBalanceOf(_owner).sub(_amountPower));
var (, left, ) = downs(_owner);
uint256 total = _amountPower.add(left);
_setDownRequest(_owner, total, total, now);
}
// executes a powerdown request
function downTick(address _holder, uint256 _now) public onlyPower whenNotPaused {
var (total, left, start) = downs(_holder);
uint256 amountPow = _vestedDown(total, left, start, _now);
// prevent power down in tiny steps
uint256 minStep = total.div(10);
require(left <= minStep || minStep <= amountPow);
// calculate token amount representing share of power
uint256 amountBabz = amountPow.mul(completeSupply()).div(authorizedPower());
// transfer power and tokens
_setOutstandingPower(outstandingPower().sub(amountPow));
left = left.sub(amountPow);
_setPowerPool(powerPool().sub(amountBabz));
_setActiveSupply(activeSupply().add(amountBabz));
_setBabzBalanceOf(_holder, babzBalanceOf(_holder).add(amountBabz));
// down request completed
if (left == 0) {
start = 0;
total = 0;
}
// TODO
_setDownRequest(_holder, total, left, start);
Nutz(nutzAddr).powerDown(powerAddr, _holder, amountBabz);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Controller is PowerEnabled {
function Controller(address _powerAddr, address _pullAddr, address _nutzAddr, address _storageAddr)
PowerEnabled(_powerAddr, _pullAddr, _nutzAddr, _storageAddr) {
}
function setContracts(address _storageAddr, address _nutzAddr, address _powerAddr, address _pullAddr) public onlyAdmins whenPaused {
storageAddr = _storageAddr;
nutzAddr = _nutzAddr;
powerAddr = _powerAddr;
pullAddr = _pullAddr;
}
function changeDailyLimit(uint256 _dailyLimit) public onlyAdmins {
PullPayment(pullAddr).changeDailyLimit(_dailyLimit);
}
function kill(address _newController) public onlyAdmins whenPaused {
if (powerAddr != address(0)) { Ownable(powerAddr).transferOwnership(msg.sender); }
if (pullAddr != address(0)) { Ownable(pullAddr).transferOwnership(msg.sender); }
if (nutzAddr != address(0)) { Ownable(nutzAddr).transferOwnership(msg.sender); }
if (storageAddr != address(0)) { Ownable(storageAddr).transferOwnership(msg.sender); }
selfdestruct(_newController);
}
} | 1,000,000 WEI, used as price factor
| require(nutzAddr.balance >= activeSupply().mul(1000000).div(_newSalePrice)); | 1,002,681 | [
1,
21,
16,
3784,
16,
3784,
13880,
45,
16,
1399,
487,
6205,
5578,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
2583,
12,
82,
322,
94,
3178,
18,
12296,
1545,
2695,
3088,
1283,
7675,
16411,
12,
21,
9449,
2934,
2892,
24899,
2704,
30746,
5147,
10019,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1313161554/0xEF72330b252490648D01B242eCfFbb10b3C01B61/sources/contracts/JetStaking/JetStakingV2.sol | @dev get the streams count @return streams.length | function getStreamsCount() external view virtual returns (uint256) {
return streams.length;
}
| 13,233,181 | [
1,
588,
326,
8205,
1056,
327,
8205,
18,
2469,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
10301,
1380,
1435,
3903,
1476,
5024,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
8205,
18,
2469,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2017-2018 Phillip A. Elsasser
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.24;
import "./Creatable.sol";
import "./MarketCollateralPool.sol";
import "./libraries/OrderLib.sol";
import "./libraries/MathLib.sol";
import "./tokens/MarketToken.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
/// @title MarketContract base contract implement all needed functionality for trading.
/// @notice this is the abstract base contract that all contracts should inherit from to
/// implement different oracle solutions.
/// @author Phil Elsasser <[email protected]>
contract MarketContract is Creatable {
using OrderLib for address;
using OrderLib for OrderLib.Order;
using OrderLib for OrderLib.OrderMappings;
using MathLib for int;
using MathLib for uint;
using SafeERC20 for ERC20;
using SafeERC20 for MarketToken;
enum ErrorCodes {
ORDER_EXPIRED, // past designated timestamp
ORDER_DEAD // order if fully filled or fully cancelled
}
// constants
address public MKT_TOKEN_ADDRESS;
MarketToken MKT_TOKEN;
string public CONTRACT_NAME;
address public BASE_TOKEN_ADDRESS;
uint public PRICE_CAP;
uint public PRICE_FLOOR;
uint public PRICE_DECIMAL_PLACES; // how to convert the pricing from decimal format (if valid) to integer
uint public QTY_MULTIPLIER; // multiplier corresponding to the value of 1 increment in price to token base units
uint public EXPIRATION;
// state variables
uint public lastPrice;
uint public settlementPrice;
bool public isSettled = false;
bool public isCollateralPoolContractLinked = false;
// accounting
address public marketCollateralPoolAddress;
MarketCollateralPool marketCollateralPool;
OrderLib.OrderMappings orderMappings;
// events
event UpdatedLastPrice(string price);
event ContractSettled(uint settlePrice);
event UpdatedUserBalance(address indexed user, uint balance);
event UpdatedPoolBalance(uint balance);
event Error(ErrorCodes indexed errorCode, bytes32 indexed orderHash);
// order events
event OrderFilled(
address indexed maker,
address indexed taker,
address indexed feeRecipient,
int filledQty,
uint paidMakerFee,
uint paidTakerFee,
bytes32 orderHash // should this be indexed?
);
event OrderCancelled(
address indexed maker,
address indexed feeRecipient,
int cancelledQty,
bytes32 indexed orderHash
);
/// @param contractName viewable name of this contract (BTC/ETH, LTC/ETH, etc)
/// @param creatorAddress address of the person creating the contract
/// @param marketTokenAddress address of our member token
/// @param baseTokenAddress address of the ERC20 token that will be used for collateral and pricing
/// @param contractSpecs array of unsigned integers including:
/// floorPrice minimum tradeable price of this contract, contract enters settlement if breached
/// capPrice maximum tradeable price of this contract, contract enters settlement if breached
/// priceDecimalPlaces number of decimal places to convert our queried price from a floating point to
/// an integer
/// qtyMultiplier multiply traded qty by this value from base units of collateral token.
/// expirationTimeStamp - seconds from epoch that this contract expires and enters settlement
constructor(
string contractName,
address creatorAddress,
address marketTokenAddress,
address baseTokenAddress,
uint[5] contractSpecs
) public
{
MKT_TOKEN_ADDRESS = marketTokenAddress;
MKT_TOKEN = MarketToken(marketTokenAddress);
require(MKT_TOKEN.isBalanceSufficientForContractCreation(msg.sender)); // creator must be MKT holder
PRICE_FLOOR = contractSpecs[0];
PRICE_CAP = contractSpecs[1];
require(PRICE_CAP > PRICE_FLOOR);
PRICE_DECIMAL_PLACES = contractSpecs[2];
QTY_MULTIPLIER = contractSpecs[3];
EXPIRATION = contractSpecs[4];
require(EXPIRATION > now);
CONTRACT_NAME = contractName;
BASE_TOKEN_ADDRESS = baseTokenAddress;
creator = creatorAddress;
}
/*
// EXTERNAL METHODS
*/
// @notice called by a participant wanting to trade a specific order
/// @param orderAddresses - maker, taker and feeRecipient addresses
/// @param unsignedOrderValues makerFee, takerFree, price, expirationTimeStamp, and salt (for hashing)
/// @param orderQty quantity of the order
/// @param qtyToFill quantity taker is willing to fill of original order(max)
/// @param v order signature
/// @param r order signature
/// @param s order signature
function tradeOrder(
address[3] orderAddresses,
uint[5] unsignedOrderValues,
int orderQty,
int qtyToFill,
uint8 v,
bytes32 r,
bytes32 s
) external returns (int filledQty)
{
require(isCollateralPoolContractLinked && !isSettled); // no trading past settlement
require(orderQty != 0 && qtyToFill != 0 && orderQty.isSameSign(qtyToFill)); // no zero trades, sings match
require(MKT_TOKEN.isUserEnabledForContract(this, msg.sender));
OrderLib.Order memory order = address(this).createOrder(orderAddresses, unsignedOrderValues, orderQty);
require(MKT_TOKEN.isUserEnabledForContract(this, order.maker));
// taker can be anyone, or specifically the caller!
require(order.taker == address(0) || order.taker == msg.sender);
// do not allow self trade
require(order.maker != address(0) && order.maker != msg.sender);
require(
order.maker.isValidSignature(
order.orderHash,
v,
r,
s
));
if (now >= order.expirationTimeStamp) {
emit Error(ErrorCodes.ORDER_EXPIRED, order.orderHash);
return 0;
}
int remainingQty = orderQty.subtract(getQtyFilledOrCancelledFromOrder(order.orderHash));
if (remainingQty == 0) { // there is no qty remaining - cannot fill!
emit Error(ErrorCodes.ORDER_DEAD, order.orderHash);
return 0;
}
filledQty = MathLib.absMin(remainingQty, qtyToFill);
marketCollateralPool.updatePositions(
order.maker,
msg.sender,
filledQty,
order.price
);
orderMappings.addFilledQtyToOrder(order.orderHash, filledQty);
uint paidMakerFee = 0;
uint paidTakerFee = 0;
if (order.feeRecipient != address(0)) {
// we need to transfer fees to recipient
uint filledAbsQty = filledQty.abs();
uint orderAbsQty = filledQty.abs();
if (order.makerFee > 0) {
paidMakerFee = order.makerFee.divideFractional(filledAbsQty, orderAbsQty);
MKT_TOKEN.safeTransferFrom(
order.maker,
order.feeRecipient,
paidMakerFee
);
}
if (order.takerFee > 0) {
paidTakerFee = order.takerFee.divideFractional(filledAbsQty, orderAbsQty);
MKT_TOKEN.safeTransferFrom(
msg.sender,
order.feeRecipient,
paidTakerFee
);
}
}
emit OrderFilled(
order.maker,
msg.sender,
order.feeRecipient,
filledQty,
paidMakerFee,
paidTakerFee,
order.orderHash
);
return filledQty;
}
/// @notice called by the maker of an order to attempt to cancel the order before its expiration time stamp
/// @param orderAddresses - maker, taker and feeRecipient addresses
/// @param unsignedOrderValues makerFee, takerFree, price, expirationTimeStamp, and salt (for hashing)
/// @param orderQty quantity of the order
/// @param qtyToCancel quantity maker is attempting to cancel
/// @return qty that was successfully cancelled of order.
function cancelOrder(
address[3] orderAddresses,
uint[5] unsignedOrderValues,
int orderQty,
int qtyToCancel
) external returns (int qtyCancelled)
{
require(qtyToCancel != 0 && qtyToCancel.isSameSign(orderQty)); // cannot cancel 0 and signs must match
require(!isSettled);
OrderLib.Order memory order = address(this).createOrder(orderAddresses, unsignedOrderValues, orderQty);
require(order.maker == msg.sender); // only maker can cancel standing order
if (now >= order.expirationTimeStamp) {
emit Error(ErrorCodes.ORDER_EXPIRED, order.orderHash);
return 0;
}
int remainingQty = orderQty.subtract(getQtyFilledOrCancelledFromOrder(order.orderHash));
if (remainingQty == 0) { // there is no qty remaining to cancel order is dead
emit Error(ErrorCodes.ORDER_DEAD, order.orderHash);
return 0;
}
qtyCancelled = MathLib.absMin(qtyToCancel, remainingQty); // we can only cancel what remains
orderMappings.addCancelledQtyToOrder(order.orderHash, qtyCancelled);
emit OrderCancelled(
order.maker,
order.feeRecipient,
qtyCancelled,
order.orderHash
);
return qtyCancelled;
}
/// @notice allows the creator to link a collateral pool contract to this trading contract.
/// can only be called once if successful. Trading cannot commence until this is completed.
/// @param poolAddress deployed address of the unique collateral pool for this contract.
function setCollateralPoolContractAddress(address poolAddress) external onlyCreator {
require(!isCollateralPoolContractLinked); // address has not been set previously
require(poolAddress != address(0)); // not trying to set it to null addr.
marketCollateralPool = MarketCollateralPool(poolAddress);
require(marketCollateralPool.linkedAddress() == address(this)); // ensure pool set up correctly.
marketCollateralPoolAddress = poolAddress;
isCollateralPoolContractLinked = true;
}
/* Currently no pre-funding is required.
/// @notice after contract settlement the contract creator can reclaim any
/// unused ethereum balance from this contract that was provided for oracle query costs / gas.
function reclaimUnusedEtherBalance() external onlyCreator {
require(isSettled && this.balance > 0); // this contract has completed all needed queries
creator.transfer(this.balance); // return balance to the creator.
}
*/
/// @notice allows a user to request an extra query to oracle in order to push the contract into
/// settlement. A user may call this as many times as they like, since they are the ones paying for
/// the call to our oracle and post processing. This is useful for both a failsafe and as a way to
/// settle a contract early if a price cap or floor has been breached.
function requestEarlySettlement() external payable;
/*
// PUBLIC METHODS
*/
/// @notice returns the qty that is no longer available to trade for a given order
/// @param orderHash hash of order to find filled and cancelled qty
/// @return int quantity that is no longer able to filled from the supplied order hash
function getQtyFilledOrCancelledFromOrder(bytes32 orderHash) public view returns (int) {
return orderMappings.getQtyFilledOrCancelledFromOrder(orderHash);
}
/*
// PRIVATE METHODS
*/
/// @dev checks our last query price to see if our contract should enter settlement due to it being past our
// expiration date or outside of our tradeable ranges.
function checkSettlement() internal {
if (isSettled) // already settled.
return;
uint newSettlementPrice;
if (now > EXPIRATION) { // note: miners can cheat this by small increments of time (minutes, not hours)
isSettled = true; // time based expiration has occurred.
newSettlementPrice = lastPrice;
} else if (lastPrice >= PRICE_CAP) { // price is greater or equal to our cap, settle to CAP price
isSettled = true;
newSettlementPrice = PRICE_CAP;
} else if (lastPrice <= PRICE_FLOOR) { // price is lesser or equal to our floor, settle to FLOOR price
isSettled = true;
newSettlementPrice = PRICE_FLOOR;
}
if (isSettled) {
settleContract(newSettlementPrice);
}
}
/// @dev records our final settlement price and fires needed events.
/// @param finalSettlementPrice final query price at time of settlement
function settleContract(uint finalSettlementPrice) private {
settlementPrice = finalSettlementPrice;
emit ContractSettled(finalSettlementPrice);
}
}
| price is greater or equal to our cap, settle to CAP price
| } else if (lastPrice >= PRICE_CAP) { | 971,429 | [
1,
8694,
353,
6802,
578,
3959,
358,
3134,
3523,
16,
444,
5929,
358,
29720,
6205,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
289,
469,
309,
261,
2722,
5147,
1545,
10365,
1441,
67,
17296,
13,
288,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { LibLoans } from "./libraries/LibLoans.sol";
import { LibEscrow } from "../escrow/libraries/LibEscrow.sol";
import {
EnumerableSet
} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
// Storage
import { Loan, LoanDebt, LoanTerms } from "../storage/market.sol";
contract LoanDataFacet {
/**
* @notice Returns the information about the given {loanID}.
* @param loanID The loan ID to get information for.
* @return loan_ The loan data.
*/
function getLoan(uint256 loanID) external view returns (Loan memory loan_) {
loan_ = LibLoans.s().loans[loanID];
}
/**
* @notice DEPRECATED
* @notice Returns the terms for a specified loan.
* @param loanID The loan ID to get the total amount owed.
* @return LoanTerms The terms that the loan weer created with.
*/
function getLoanTerms(uint256 loanID)
external
view
returns (LoanTerms memory)
{
return LibLoans.terms(loanID);
}
/**
* @notice Returns the loan IDs created by the {borrower} account.
* @param borrower The account to get loan IDs for.
* @return loanIDs The IDs for loans created by the {borrower}
*/
function getBorrowerLoans(address borrower)
external
view
returns (uint128[] memory loanIDs)
{
return LibLoans.s().borrowerLoans[borrower];
}
/**
* @notice Returns the debt owed for a specified loan.
* @param loanID The loan ID to get the total amount owed.
* @return LoanDebt The principal and interest owed amount.
*/
function getDebtOwed(uint256 loanID)
external
view
returns (LoanDebt memory)
{
return LibLoans.debt(loanID);
}
/**
* @notice Returns the total amount owed for a specified loan.
* @param loanID The loan ID to get the total amount owed.
* @return uint256 The total owed amount.
*/
function getTotalOwed(uint256 loanID) external view returns (uint256) {
return LibLoans.getTotalOwed(loanID);
}
/**
* @notice Returns the amount of interest owed for a given loan and loan amount.
* @param loanID The loan ID to get the owed interest.
* @param amountBorrow The principal of the loan to take out.
* @return uint256 The interest owed.
*/
function getInterestOwedFor(uint256 loanID, uint256 amountBorrow)
external
view
returns (uint256)
{
return LibLoans.getInterestOwedFor(loanID, amountBorrow);
}
/**
* @notice it returns the collateral needed for a loan
* @param loanID the identifier of the loan ID to retrieve collateral from
* @return neededInLendingTokens total collateral needed in lending tokens
* @return neededInCollateralTokens total collateral needed in collateral tokens
* @return escrowLoanValue total collateral needed in loan value
*/
function getCollateralNeededInfo(uint256 loanID)
external
returns (
uint256 neededInLendingTokens,
uint256 neededInCollateralTokens,
uint256 escrowLoanValue
)
{
return LibLoans.getCollateralNeededInfo(loanID);
}
/**
* @notice it returns the typed address of a loan escrow
* @param loanID the identifier of the respective escrow's loan
* @return escrow_ the typed address of the returned ILoanEscrow
*/
function getLoanEscrow(uint256 loanID)
external
view
returns (address escrow_)
{
escrow_ = address(LibLoans.s().loanEscrows[loanID]);
}
/**
* @notice it returns the escrow's total value by calculating the value all the escrow tokens
* @param loanID the identifier of the respective escrow's loan
* @return the total value of the loan escrow
*/
function getLoanEscrowValue(uint256 loanID) external returns (uint256) {
return LibEscrow.calculateTotalValue(loanID);
}
/**
* @notice it returns the total escrow tokens held by an escrow
* @param loanID the identifier of the respective escrow's loan
* @return tokens_ the tokens held at the escrow loan
*/
function getEscrowTokens(uint256 loanID)
external
view
returns (address[] memory tokens_)
{
EnumerableSet.AddressSet storage escrowTokens = LibEscrow
.getEscrowTokens(loanID);
tokens_ = new address[](EnumerableSet.length(escrowTokens));
for (uint256 i; i < tokens_.length; i++) {
tokens_[i] = EnumerableSet.at(escrowTokens, i);
}
}
}
| * @notice Returns the amount of interest owed for a given loan and loan amount. @param loanID The loan ID to get the owed interest. @param amountBorrow The principal of the loan to take out. @return uint256 The interest owed./ | function getInterestOwedFor(uint256 loanID, uint256 amountBorrow)
external
view
returns (uint256)
{
return LibLoans.getInterestOwedFor(loanID, amountBorrow);
}
| 2,549,871 | [
1,
1356,
326,
3844,
434,
16513,
2523,
329,
364,
279,
864,
28183,
471,
28183,
3844,
18,
225,
28183,
734,
1021,
28183,
1599,
358,
336,
326,
2523,
329,
16513,
18,
225,
3844,
38,
15318,
1021,
8897,
434,
326,
28183,
358,
4862,
596,
18,
327,
2254,
5034,
1021,
16513,
2523,
329,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
29281,
3494,
329,
1290,
12,
11890,
5034,
28183,
734,
16,
2254,
5034,
3844,
38,
15318,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
10560,
1504,
634,
18,
588,
29281,
3494,
329,
1290,
12,
383,
304,
734,
16,
3844,
38,
15318,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.