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/80001/0xd278A4A079e656a6bCDdD8a3144f9851becB906e/sources/project_/contracts/extensions/artifacts/ArtifactsTokensERC1155AddressUpgradeable.sol
* @notice Get artifacts tokens ERC1155 contract address @return Address of artifacts tokens contract/
function getArtifactsTokensERC1155Address() public virtual view returns(address) { return(_artifactsTokensERC1155Address); }
5,641,065
[ 1, 967, 16259, 2430, 4232, 39, 2499, 2539, 6835, 1758, 282, 327, 5267, 434, 16259, 2430, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 16981, 5157, 654, 39, 2499, 2539, 1887, 1435, 1071, 5024, 1476, 1135, 12, 2867, 13, 288, 203, 3639, 327, 24899, 30347, 5157, 654, 39, 2499, 2539, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/83/0x48ef19252C6c59c5CF1e5Bd87DAeE0A2c5BA7cEE/sources/contracts/CToken/CToken.sol
We calculate the new total supply and redeemer balance, checking for underflow: totalSupplyNew = totalSupply - redeemTokens accountTokensNew = accountTokens[redeemer] - redeemTokens/
(vars.mathErr, vars.totalSupplyNew) = totalSupply.subUInt(vars.redeemTokens);
9,556,643
[ 1, 3218, 4604, 326, 394, 2078, 14467, 471, 283, 24903, 264, 11013, 16, 6728, 364, 3613, 2426, 30, 225, 2078, 3088, 1283, 1908, 273, 2078, 3088, 1283, 300, 283, 24903, 5157, 225, 2236, 5157, 1908, 273, 2236, 5157, 63, 266, 24903, 264, 65, 300, 283, 24903, 5157, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 261, 4699, 18, 15949, 2524, 16, 4153, 18, 4963, 3088, 1283, 1908, 13, 273, 2078, 3088, 1283, 18, 1717, 14342, 12, 4699, 18, 266, 24903, 5157, 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 ]
./partial_match/100/0x3c942B969C85cfd24942ECE39de6F843767F1755/sources/ClearingHouseViewer.sol
File: @opengsn/gsn/contracts/utils/MinLibBytes.sol minimal bytes manipulation required by GSN a minimal subset from 0x/LibBytes solhint-disable no-inline-assembly */truncate the given parameter (in-place) if its length is above the given maximum length do nothing otherwise.NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter.
library MinLibBytes { function swapInput( Dir _dir, Decimal.decimal calldata _quoteAssetAmount, Decimal.decimal calldata _baseAssetAmountLimit ) external returns (Decimal.decimal memory); function swapOutput( Dir _dir, Decimal.decimal calldata _baseAssetAmount, Decimal.decimal calldata _quoteAssetAmountLimit, bool _skipFluctuationCheck ) external returns (Decimal.decimal memory); function migrateLiquidity(Decimal.decimal calldata _liquidityMultiplier) external; function shutdown() external; function settleFunding() external returns (SignedDecimal.signedDecimal memory); function calcFee(Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory, Decimal.decimal memory); function calcBaseAssetAfterLiquidityMigration( SignedDecimal.signedDecimal memory _baseAssetAmount, Decimal.decimal memory _fromQuoteReserve, Decimal.decimal memory _fromBaseReserve ) external view returns (SignedDecimal.signedDecimal memory); function getInputTwap(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputTwap(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPrice(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputPrice(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPriceWithReserves( Dir _dir, Decimal.decimal memory _quoteAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getOutputPriceWithReserves( Dir _dir, Decimal.decimal memory _baseAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getReserve() external view returns (Decimal.decimal memory, Decimal.decimal memory); function getLiquidityHistoryLength() external view returns (uint256); function quoteAsset() external view returns (IERC20); function open() external view returns (bool); function getSettlementPrice() external view returns (Decimal.decimal memory); function getBaseAssetDeltaThisFundingPeriod() external view returns (SignedDecimal.signedDecimal memory); function getCumulativeNotional() external view returns (SignedDecimal.signedDecimal memory); function getMaxHoldingBaseAsset() external view returns (Decimal.decimal memory); function getLiquidityChangedSnapshots(uint256 i) external view returns (LiquidityChangedSnapshot memory); } pragma solidity 0.6.9; } pragma solidity ^0.6.2; function truncateInPlace(bytes memory data, uint256 maxlen) internal pure { if (data.length > maxlen) { assembly { mstore(data, maxlen) } } } function swapInput( Dir _dir, Decimal.decimal calldata _quoteAssetAmount, Decimal.decimal calldata _baseAssetAmountLimit ) external returns (Decimal.decimal memory); function swapOutput( Dir _dir, Decimal.decimal calldata _baseAssetAmount, Decimal.decimal calldata _quoteAssetAmountLimit, bool _skipFluctuationCheck ) external returns (Decimal.decimal memory); function migrateLiquidity(Decimal.decimal calldata _liquidityMultiplier) external; function shutdown() external; function settleFunding() external returns (SignedDecimal.signedDecimal memory); function calcFee(Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory, Decimal.decimal memory); function calcBaseAssetAfterLiquidityMigration( SignedDecimal.signedDecimal memory _baseAssetAmount, Decimal.decimal memory _fromQuoteReserve, Decimal.decimal memory _fromBaseReserve ) external view returns (SignedDecimal.signedDecimal memory); function getInputTwap(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputTwap(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPrice(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputPrice(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPriceWithReserves( Dir _dir, Decimal.decimal memory _quoteAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getOutputPriceWithReserves( Dir _dir, Decimal.decimal memory _baseAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getReserve() external view returns (Decimal.decimal memory, Decimal.decimal memory); function getLiquidityHistoryLength() external view returns (uint256); function quoteAsset() external view returns (IERC20); function open() external view returns (bool); function getSettlementPrice() external view returns (Decimal.decimal memory); function getBaseAssetDeltaThisFundingPeriod() external view returns (SignedDecimal.signedDecimal memory); function getCumulativeNotional() external view returns (SignedDecimal.signedDecimal memory); function getMaxHoldingBaseAsset() external view returns (Decimal.decimal memory); function getLiquidityChangedSnapshots(uint256 i) external view returns (LiquidityChangedSnapshot memory); } pragma solidity 0.6.9; } pragma solidity ^0.6.2; function truncateInPlace(bytes memory data, uint256 maxlen) internal pure { if (data.length > maxlen) { assembly { mstore(data, maxlen) } } } function swapInput( Dir _dir, Decimal.decimal calldata _quoteAssetAmount, Decimal.decimal calldata _baseAssetAmountLimit ) external returns (Decimal.decimal memory); function swapOutput( Dir _dir, Decimal.decimal calldata _baseAssetAmount, Decimal.decimal calldata _quoteAssetAmountLimit, bool _skipFluctuationCheck ) external returns (Decimal.decimal memory); function migrateLiquidity(Decimal.decimal calldata _liquidityMultiplier) external; function shutdown() external; function settleFunding() external returns (SignedDecimal.signedDecimal memory); function calcFee(Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory, Decimal.decimal memory); function calcBaseAssetAfterLiquidityMigration( SignedDecimal.signedDecimal memory _baseAssetAmount, Decimal.decimal memory _fromQuoteReserve, Decimal.decimal memory _fromBaseReserve ) external view returns (SignedDecimal.signedDecimal memory); function getInputTwap(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputTwap(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPrice(Dir _dir, Decimal.decimal calldata _quoteAssetAmount) external view returns (Decimal.decimal memory); function getOutputPrice(Dir _dir, Decimal.decimal calldata _baseAssetAmount) external view returns (Decimal.decimal memory); function getInputPriceWithReserves( Dir _dir, Decimal.decimal memory _quoteAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getOutputPriceWithReserves( Dir _dir, Decimal.decimal memory _baseAssetAmount, Decimal.decimal memory _quoteAssetPoolAmount, Decimal.decimal memory _baseAssetPoolAmount ) external pure returns (Decimal.decimal memory); function getReserve() external view returns (Decimal.decimal memory, Decimal.decimal memory); function getLiquidityHistoryLength() external view returns (uint256); function quoteAsset() external view returns (IERC20); function open() external view returns (bool); function getSettlementPrice() external view returns (Decimal.decimal memory); function getBaseAssetDeltaThisFundingPeriod() external view returns (SignedDecimal.signedDecimal memory); function getCumulativeNotional() external view returns (SignedDecimal.signedDecimal memory); function getMaxHoldingBaseAsset() external view returns (Decimal.decimal memory); function getLiquidityChangedSnapshots(uint256 i) external view returns (LiquidityChangedSnapshot memory); } pragma solidity 0.6.9; } pragma solidity ^0.6.2; function truncateInPlace(bytes memory data, uint256 maxlen) internal pure { if (data.length > maxlen) { assembly { mstore(data, maxlen) } } } function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require(b.length >= index + 20, "readAddress: data too short"); index += 20; assembly { result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function readAddress(bytes memory b, uint256 index) internal pure returns (address result) { require(b.length >= index + 20, "readAddress: data too short"); index += 20; assembly { result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "readBytes32: data too short"); assembly { result := mload(add(b, add(index, 32))) } return result; } function readBytes32(bytes memory b, uint256 index) internal pure returns (bytes32 result) { require(b.length >= index + 32, "readBytes32: data too short"); assembly { result := mload(add(b, add(index, 32))) } return result; } function readUint256(bytes memory b, uint256 index) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "readBytes4: data too short"); assembly { result := mload(add(b, add(index, 32))) result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } function readBytes4(bytes memory b, uint256 index) internal pure returns (bytes4 result) { require(b.length >= index + 4, "readBytes4: data too short"); assembly { result := mload(add(b, add(index, 32))) result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } }
16,663,823
[ 1, 812, 30, 632, 3190, 564, 82, 19, 564, 82, 19, 16351, 87, 19, 5471, 19, 2930, 5664, 2160, 18, 18281, 16745, 1731, 27029, 1931, 635, 611, 13653, 279, 16745, 7931, 628, 374, 92, 19, 5664, 2160, 3704, 11317, 17, 8394, 1158, 17, 10047, 17, 28050, 342, 27201, 326, 864, 1569, 261, 267, 17, 964, 13, 309, 2097, 769, 353, 5721, 326, 864, 4207, 769, 741, 5083, 3541, 18, 17857, 30, 18035, 560, 1894, 87, 3308, 326, 707, 353, 9350, 315, 84, 594, 3113, 1496, 518, 5467, 3991, 5612, 2097, 1569, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5444, 5664, 2160, 288, 203, 565, 445, 7720, 1210, 12, 203, 3639, 8446, 389, 1214, 16, 203, 3639, 11322, 18, 12586, 745, 892, 389, 6889, 6672, 6275, 16, 203, 3639, 11322, 18, 12586, 745, 892, 389, 1969, 6672, 6275, 3039, 203, 565, 262, 3903, 1135, 261, 5749, 18, 12586, 3778, 1769, 203, 203, 565, 445, 7720, 1447, 12, 203, 3639, 8446, 389, 1214, 16, 203, 3639, 11322, 18, 12586, 745, 892, 389, 1969, 6672, 6275, 16, 203, 3639, 11322, 18, 12586, 745, 892, 389, 6889, 6672, 6275, 3039, 16, 203, 3639, 1426, 389, 7457, 2340, 853, 11407, 1564, 203, 565, 262, 3903, 1135, 261, 5749, 18, 12586, 3778, 1769, 203, 203, 565, 445, 13187, 48, 18988, 24237, 12, 5749, 18, 12586, 745, 892, 389, 549, 372, 24237, 23365, 13, 3903, 31, 203, 203, 565, 445, 5731, 1435, 3903, 31, 203, 203, 565, 445, 444, 5929, 42, 14351, 1435, 3903, 1135, 261, 12294, 5749, 18, 5679, 5749, 3778, 1769, 203, 203, 565, 445, 7029, 14667, 12, 5749, 18, 12586, 745, 892, 389, 6889, 6672, 6275, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 5749, 18, 12586, 3778, 16, 11322, 18, 12586, 3778, 1769, 203, 203, 203, 565, 445, 7029, 2171, 6672, 4436, 48, 18988, 24237, 10224, 12, 203, 3639, 16724, 5749, 18, 5679, 5749, 3778, 389, 1969, 6672, 6275, 16, 203, 3639, 11322, 18, 12586, 3778, 389, 2080, 10257, 607, 6527, 16, 203, 3639, 11322, 18, 12586, 3778, 389, 2080, 2171, 607, 6527, 203, 565, 262, 3903, 1476, 1135, 261, 12294, 2 ]
./full_match/3/0xa11D997a852fb8A8aC2a4578412a4f929D8A486b/sources/contracts/1_Storage.sol
* @dev Return value @return value of 'number'/
function get() public view returns (uint8){ return number; }
8,181,116
[ 1, 990, 460, 327, 460, 434, 296, 2696, 11, 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, 336, 1435, 1071, 1476, 1135, 261, 11890, 28, 15329, 203, 3639, 327, 1300, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x67812f190274301Ef144a4700A564C2A2D4b3cc1/sources/contracts/flokitest.sol
antibot - first 2 blocks
if(launchedAt>0 && (launchedAt + deadBlocks) > block.number){ _isSniper[to]=true; }
843,455
[ 1, 970, 495, 352, 300, 1122, 576, 4398, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 12, 11821, 22573, 861, 34, 20, 597, 261, 11821, 22573, 861, 397, 8363, 6450, 13, 405, 1203, 18, 2696, 15329, 203, 7734, 389, 291, 10461, 77, 457, 63, 869, 65, 33, 3767, 31, 203, 3639, 289, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x9d7781bECb2796521bEbE251A6BB960B11e19120/sources/AntiMEV.sol
blocks to mine before 2nd tx
uint256 public _mineBlocks = 3;
16,816,984
[ 1, 7996, 358, 312, 558, 1865, 576, 4880, 2229, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 389, 3081, 6450, 273, 890, 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 ]
/** * The Consumer Contract Wallet * Copyright (C) 2018 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.4.25; /// @title The Controller interface provides access to an external list of controllers. interface IController { function isController(address) external view returns (bool); } /// @title Controller stores a list of controller addresses that can be used for authentication in other contracts. contract Controller is IController { event AddedController(address _sender, address _controller); event RemovedController(address _sender, address _controller); mapping (address => bool) private _isController; uint private _controllerCount; /// @dev Constructor initializes the list of controllers with the provided address. /// @param _account address to add to the list of controllers. constructor(address _account) public { _addController(_account); } /// @dev Checks if message sender is a controller. modifier onlyController() { require(isController(msg.sender), "sender is not a controller"); _; } /// @dev Add a new controller to the list of controllers. /// @param _account address to add to the list of controllers. function addController(address _account) external onlyController { _addController(_account); } /// @dev Remove a controller from the list of controllers. /// @param _account address to remove from the list of controllers. function removeController(address _account) external onlyController { _removeController(_account); } /// @return true if the provided account is a controller. function isController(address _account) public view returns (bool) { return _isController[_account]; } /// @return the current number of controllers. function controllerCount() public view returns (uint) { return _controllerCount; } /// @dev Internal-only function that adds a new controller. function _addController(address _account) internal { require(!_isController[_account], "provided account is already a controller"); _isController[_account] = true; _controllerCount++; emit AddedController(msg.sender, _account); } /// @dev Internal-only function that removes an existing controller. function _removeController(address _account) internal { require(_isController[_account], "provided account is not a controller"); require(_controllerCount > 1, "cannot remove the last controller"); _isController[_account] = false; _controllerCount--; emit RemovedController(msg.sender, _account); } } /** * BSD 2-Clause License * * Copyright (c) 2018, True Names Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public; function setResolver(bytes32 node, address resolver) public; function setOwner(bytes32 node, address owner) public; function setTTL(bytes32 node, uint64 ttl) public; function owner(bytes32 node) public view returns (address); function resolver(bytes32 node) public view returns (address); function ttl(bytes32 node) public view returns (uint64); } /// @title Resolver returns the controller contract address. interface IResolver { function addr(bytes32) external view returns (address); } /// @title Controllable implements access control functionality based on a controller set in ENS. contract Controllable { /// @dev _ENS points to the ENS registry smart contract. ENS private _ENS; /// @dev Is the registered ENS name of the controller contract. bytes32 private _node; /// @dev Constructor initializes the controller contract object. /// @param _ens is the address of the ENS. /// @param _controllerName is the ENS name of the Controller. constructor(address _ens, bytes32 _controllerName) internal { _ENS = ENS(_ens); _node = _controllerName; } /// @dev Checks if message sender is the controller. modifier onlyController() { require(_isController(msg.sender), "sender is not a controller"); _; } /// @return true if the provided account is the controller. function _isController(address _account) internal view returns (bool) { return IController(IResolver(_ENS.resolver(_node)).addr(_node)).isController(_account); } } /// @title Date provides date parsing functionality. contract Date { bytes32 constant private JANUARY = keccak256("Jan"); bytes32 constant private FEBRUARY = keccak256("Feb"); bytes32 constant private MARCH = keccak256("Mar"); bytes32 constant private APRIL = keccak256("Apr"); bytes32 constant private MAY = keccak256("May"); bytes32 constant private JUNE = keccak256("Jun"); bytes32 constant private JULY = keccak256("Jul"); bytes32 constant private AUGUST = keccak256("Aug"); bytes32 constant private SEPTEMBER = keccak256("Sep"); bytes32 constant private OCTOBER = keccak256("Oct"); bytes32 constant private NOVEMBER = keccak256("Nov"); bytes32 constant private DECEMBER = keccak256("Dec"); /// @return the number of the month based on its name. /// @param _month the first three letters of a month's name e.g. "Jan". function _monthToNumber(string _month) internal pure returns (uint8) { bytes32 month = keccak256(abi.encodePacked(_month)); if (month == JANUARY) { return 1; } else if (month == FEBRUARY) { return 2; } else if (month == MARCH) { return 3; } else if (month == APRIL) { return 4; } else if (month == MAY) { return 5; } else if (month == JUNE) { return 6; } else if (month == JULY) { return 7; } else if (month == AUGUST) { return 8; } else if (month == SEPTEMBER) { return 9; } else if (month == OCTOBER) { return 10; } else if (month == NOVEMBER) { return 11; } else if (month == DECEMBER) { return 12; } else { revert("not a valid month"); } } } // <ORACLIZE_API> // Release targetted at solc 0.4.25 to silence compiler warning/error messages, compatible down to 0.4.22 /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.22 to 0.4.25 (stable builds), please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.22;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; // Following should never be reached with a preceding return, however // this is just a placeholder function, ideally meant to be defined in // child contract when proofs are used myid; result; proof; // Silence compiler warnings oraclize = OraclizeI(0); // Additional compiler silence about making function pure/view. } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) view internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> /// @title JSON provides JSON parsing functionality. contract JSON is usingOraclize{ using strings for *; bytes32 constant private prefixHash = keccak256("{\"ETH\":"); /// @dev Extracts JSON rate value from the response object. /// @param _json body of the JSON response from the CryptoCompare API. function parseRate(string _json) public pure returns (string) { uint json_len = abi.encodePacked(_json).length; //{"ETH":}.length = 8, assuming a (maximum of) 18 digit prevision require(json_len > 8 && json_len <= 28, "misformatted input"); bytes memory jsonPrefix = new bytes(7); copyBytes(abi.encodePacked(_json), 0, 7, jsonPrefix, 0); require(keccak256(jsonPrefix) == prefixHash, "prefix mismatch"); strings.slice memory body = _json.toSlice(); body.split(":".toSlice()); //we are sure that ':' is included in the string, body now contains the rate+'}' json_len = body._len; body.until("}".toSlice()); require(body._len == json_len-1,"not json format"); //ensure that the json is properly terminated with a '}' return body.toString(); } } /// @title ParseIntScientific provides floating point in scientific notation (e.g. e-5) parsing functionality. contract ParseIntScientific { using SafeMath for uint256; byte constant private PLUS_ASCII = byte(43); //decimal value of '+' byte constant private DASH_ASCII = byte(45); //decimal value of '-' byte constant private DOT_ASCII = byte(46); //decimal value of '.' byte constant private ZERO_ASCII = byte(48); //decimal value of '0' byte constant private NINE_ASCII = byte(57); //decimal value of '9' byte constant private E_ASCII = byte(69); //decimal value of 'E' byte constant private e_ASCII = byte(101); //decimal value of 'e' /// @dev ParseIntScientific delegates the call to _parseIntScientific(string, uint) with the 2nd argument being 0. function _parseIntScientific(string _inString) internal pure returns (uint) { return _parseIntScientific(_inString, 0); } /// @dev ParseIntScientificWei parses a rate expressed in ETH and returns its wei denomination function _parseIntScientificWei(string _inString) internal pure returns (uint) { return _parseIntScientific(_inString, 18); } /// @dev ParseIntScientific parses a JSON standard - floating point number. /// @param _inString is input string. /// @param _magnitudeMult multiplies the number with 10^_magnitudeMult. function _parseIntScientific(string _inString, uint _magnitudeMult) internal pure returns (uint) { bytes memory inBytes = bytes(_inString); uint mint = 0; // the final uint returned uint mintDec = 0; // the uint following the decimal point uint mintExp = 0; // the exponent uint decMinted = 0; // how many decimals were 'minted'. uint expIndex = 0; // the position in the byte array that 'e' was found (if found) bool integral = false; // indicates the existence of the integral part, it should always exist (even if 0) e.g. 'e+1' or '.1' is not valid bool decimals = false; // indicates a decimal number, set to true if '.' is found bool exp = false; // indicates if the number being parsed has an exponential representation bool minus = false; // indicated if the exponent is negative bool plus = false; // indicated if the exponent is positive for (uint i = 0; i < inBytes.length; i++) { if ((inBytes[i] >= ZERO_ASCII) && (inBytes[i] <= NINE_ASCII) && (!exp)) { // 'e' not encountered yet, minting integer part or decimals if (decimals) { // '.' encountered //use safeMath in case there is an overflow mintDec = mintDec.mul(10); mintDec = mintDec.add(uint(inBytes[i]) - uint(ZERO_ASCII)); decMinted++; //keep track of the #decimals } else { // integral part (before '.') integral = true; //use safeMath in case there is an overflow mint = mint.mul(10); mint = mint.add(uint(inBytes[i]) - uint(ZERO_ASCII)); } } else if ((inBytes[i] >= ZERO_ASCII) && (inBytes[i] <= NINE_ASCII) && (exp)) { //exponential notation (e-/+) has been detected, mint the exponent mintExp = mintExp.mul(10); mintExp = mintExp.add(uint(inBytes[i]) - uint(ZERO_ASCII)); } else if (inBytes[i] == DOT_ASCII) { //an integral part before should always exist before '.' require(integral, "missing integral part"); // an extra decimal point makes the format invalid require(!decimals, "duplicate decimal point"); //the decimal point should always be before the exponent require(!exp, "decimal after exponent"); decimals = true; } else if (inBytes[i] == DASH_ASCII) { // an extra '-' should be considered an invalid character require(!minus, "duplicate -"); require(!plus, "extra sign"); require(expIndex + 1 == i, "- sign not immediately after e"); minus = true; } else if (inBytes[i] == PLUS_ASCII) { // an extra '+' should be considered an invalid character require(!plus, "duplicate +"); require(!minus, "extra sign"); require(expIndex + 1 == i, "+ sign not immediately after e"); plus = true; } else if ((inBytes[i] == E_ASCII) || (inBytes[i] == e_ASCII)) { //an integral part before should always exist before 'e' require(integral, "missing integral part"); // an extra 'e' or 'E' should be considered an invalid character require(!exp, "duplicate exponent symbol"); exp = true; expIndex = i; } else { revert("invalid digit"); } } if (minus || plus) { // end of string e[x|-] without specifying the exponent require(i > expIndex + 2); } else if (exp) { // end of string (e) without specifying the exponent require(i > expIndex + 1); } if (minus) { // e^(-x) if (mintExp >= _magnitudeMult) { // the (negative) exponent is bigger than the given parameter for "shifting left". // use integer division to reduce the precision. require(mintExp - _magnitudeMult < 78, "exponent > 77"); // mint /= 10 ** (mintExp - _magnitudeMult); return mint; } else { // the (negative) exponent is smaller than the given parameter for "shifting left". //no need for underflow check _magnitudeMult = _magnitudeMult - mintExp; } } else { // e^(+x), positive exponent or no exponent // just shift left as many times as indicated by the exponent and the shift parameter _magnitudeMult = _magnitudeMult.add(mintExp); } if (_magnitudeMult >= decMinted) { // the decimals are fewer or equal than the shifts: use all of them // shift number and add the decimals at the end // include decimals if present in the original input require(decMinted < 78, "more than 77 decimal digits parsed"); // mint = mint.mul(10 ** (decMinted)); mint = mint.add(mintDec); //// add zeros at the end if the decimals were fewer than #_magnitudeMult require(_magnitudeMult - decMinted < 78, "exponent > 77"); // mint = mint.mul(10 ** (_magnitudeMult - decMinted)); } else { // the decimals are more than the #_magnitudeMult shifts // use only the ones needed, discard the rest decMinted -= _magnitudeMult; require(decMinted < 78, "more than 77 decimal digits parsed"); // mintDec /= 10 ** (decMinted); // shift number and add the decimals at the end require(_magnitudeMult < 78, "more than 77 decimal digits parsed"); // mint = mint.mul(10 ** (_magnitudeMult)); mint = mint.add(mintDec); } return mint; } } /* * Copyright 2016 Nick Johnson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if(shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if(b < 0xE0) { l = 2; } else if(b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } /** * The MIT License (MIT) * * Copyright (c) 2016 Smart Contract Solutions, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * This method was modified from the GPLv3 solidity code found in this repository * https://github.com/vcealicu/melonport-price-feed/blob/master/pricefeed/PriceFeed.sol */ /// @title Base64 provides base 64 decoding functionality. contract Base64 { bytes constant BASE64_DECODE_CHAR = hex"000000000000000000000000000000000000000000000000000000000000000000000000000000000000003e003e003f3435363738393a3b3c3d00000000000000000102030405060708090a0b0c0d0e0f10111213141516171819000000003f001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233"; /// @return decoded array of bytes. /// @param _encoded base 64 encoded array of bytes. function _base64decode(bytes _encoded) internal pure returns (bytes) { byte v1; byte v2; byte v3; byte v4; uint length = _encoded.length; bytes memory result = new bytes(length); uint index; // base64 encoded strings can't be length 0 and they must be divisble by 4 require(length > 0 && length % 4 == 0, "invalid base64 encoding"); if (keccak256(abi.encodePacked(_encoded[length - 2])) == keccak256("=")) { length -= 2; } else if (keccak256(abi.encodePacked(_encoded[length - 1])) == keccak256("=")) { length -= 1; } uint count = length >> 2 << 2; for (uint i = 0; i < count;) { v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; v3 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; v4 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; result[index++] = (v1 << 2 | v2 >> 4) & 255; result[index++] = (v2 << 4 | v3 >> 2) & 255; result[index++] = (v3 << 6 | v4) & 255; } if (length - count == 2) { v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; result[index++] = (v1 << 2 | v2 >> 4) & 255; } else if (length - count == 3) { v1 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; v2 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; v3 = BASE64_DECODE_CHAR[uint(_encoded[i++])]; result[index++] = (v1 << 2 | v2 >> 4) & 255; result[index++] = (v2 << 4 | v3 >> 2) & 255; } // Set to correct length. assembly { mstore(result, index) } return result; } } /// @title Oracle converts ERC20 token amounts into equivalent ether amounts based on cryptocurrency exchange rates. interface IOracle { function convert(address, uint) external view returns (bool, uint); } /// @title Oracle provides asset exchange rates and conversion functionality. contract Oracle is usingOraclize, Base64, Date, JSON, Controllable, ParseIntScientific, IOracle { using strings for *; using SafeMath for uint256; /*******************/ /* Events */ /*****************/ event AddedToken(address _sender, address _token, string _symbol, uint _magnitude); event RemovedToken(address _sender, address _token); event UpdatedTokenRate(address _sender, address _token, uint _rate); event SetGasPrice(address _sender, uint _gasPrice); event Converted(address _sender, address _token, uint _amount, uint _ether); event RequestedUpdate(string _symbol); event FailedUpdateRequest(string _reason); event VerifiedProof(bytes _publicKey, string _result); event SetCryptoComparePublicKey(address _sender, bytes _publicKey); /**********************/ /* Constants */ /********************/ uint constant private PROOF_LEN = 165; uint constant private ECDSA_SIG_LEN = 65; uint constant private ENCODING_BYTES = 2; uint constant private HEADERS_LEN = PROOF_LEN - 2 * ENCODING_BYTES - ECDSA_SIG_LEN; // 2 bytes encoding headers length + 2 for signature. uint constant private DIGEST_BASE64_LEN = 44; //base64 encoding of the SHA256 hash (32-bytes) of the result: fixed length. uint constant private DIGEST_OFFSET = HEADERS_LEN - DIGEST_BASE64_LEN; // the starting position of the result hash in the headers string. uint constant private MAX_BYTE_SIZE = 256; //for calculating length encoding struct Token { string symbol; // Token symbol uint magnitude; // 10^decimals uint rate; // Token exchange rate in wei uint lastUpdate; // Time of the last rate update bool exists; // Flags if the struct is empty or not } mapping(address => Token) public tokens; address[] private _tokenAddresses; bytes public APIPublicKey; mapping(bytes32 => address) private _queryToToken; /// @dev Construct the oracle with multiple controllers, address resolver and custom gas price. /// @dev _resolver is the oraclize address resolver contract address. /// @param _ens is the address of the ENS. /// @param _controllerName is the ENS name of the Controller. constructor(address _resolver, address _ens, bytes32 _controllerName) Controllable(_ens, _controllerName) public { APIPublicKey = hex"a0f4f688350018ad1b9785991c0bde5f704b005dc79972b114dbed4a615a983710bfc647ebe5a320daa28771dce6a2d104f5efa2e4a85ba3760b76d46f8571ca"; OAR = OraclizeAddrResolverI(_resolver); oraclize_setCustomGasPrice(10000000000); oraclize_setProof(proofType_Native); } /// @dev Updates the Crypto Compare public API key. function updateAPIPublicKey(bytes _publicKey) external onlyController { APIPublicKey = _publicKey; emit SetCryptoComparePublicKey(msg.sender, _publicKey); } /// @dev Sets the gas price used by oraclize query. function setCustomGasPrice(uint _gasPrice) external onlyController { oraclize_setCustomGasPrice(_gasPrice); emit SetGasPrice(msg.sender, _gasPrice); } /// @dev Convert ERC20 token amount to the corresponding ether amount (used by the wallet contract). /// @param _token ERC20 token contract address. /// @param _amount amount of token in base units. function convert(address _token, uint _amount) external view returns (bool, uint) { // Store the token in memory to save map entry lookup gas. Token storage token = tokens[_token]; // If the token exists require that its rate is not zero if (token.exists) { require(token.rate != 0, "token rate is 0"); // Safely convert the token amount to ether based on the exchange rate. // return the value and a 'true' implying that the token is protected return (true, _amount.mul(token.rate).div(token.magnitude)); } // this returns a 'false' to imply that a card is not protected return (false, 0); } /// @dev Add ERC20 tokens to the list of supported tokens. /// @param _tokens ERC20 token contract addresses. /// @param _symbols ERC20 token names. /// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token. /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received. function addTokens(address[] _tokens, bytes32[] _symbols, uint[] _magnitude, uint _updateDate) external onlyController { // Require that all parameters have the same length. require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length, "parameter lengths do not match"); // Add each token to the list of supported tokens. for (uint i = 0; i < _tokens.length; i++) { // Require that the token doesn't already exist. address token = _tokens[i]; require(!tokens[token].exists, "token already exists"); // Store the intermediate values. string memory symbol = _symbols[i].toSliceB32().toString(); uint magnitude = _magnitude[i]; // Add the token to the token list. tokens[token] = Token({ symbol : symbol, magnitude : magnitude, rate : 0, exists : true, lastUpdate: _updateDate }); // Add the token address to the address list. _tokenAddresses.push(token); // Emit token addition event. emit AddedToken(msg.sender, token, symbol, magnitude); } } /// @dev Remove ERC20 tokens from the list of supported tokens. /// @param _tokens ERC20 token contract addresses. function removeTokens(address[] _tokens) external onlyController { // Delete each token object from the list of supported tokens based on the addresses provided. for (uint i = 0; i < _tokens.length; i++) { //token must exist, reverts on duplicates as well require(tokens[_tokens[i]].exists, "token does not exist"); // Store the token address. address token = _tokens[i]; // Delete the token object. delete tokens[token]; // Remove the token address from the address list. for (uint j = 0; j < _tokenAddresses.length.sub(1); j++) { if (_tokenAddresses[j] == token) { _tokenAddresses[j] = _tokenAddresses[_tokenAddresses.length.sub(1)]; break; } } _tokenAddresses.length--; // Emit token removal event. emit RemovedToken(msg.sender, token); } } /// @dev Update ERC20 token exchange rate manually. /// @param _token ERC20 token contract address. /// @param _rate ERC20 token exchange rate in wei. /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received. function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyController { // Require that the token exists. require(tokens[_token].exists, "token does not exist"); // Update the token's rate. tokens[_token].rate = _rate; // Update the token's last update timestamp. tokens[_token].lastUpdate = _updateDate; // Emit the rate update event. emit UpdatedTokenRate(msg.sender, _token, _rate); } /// @dev Update ERC20 token exchange rates for all supported tokens. //// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback function updateTokenRates(uint _gasLimit) external payable onlyController { _updateTokenRates(_gasLimit); } //// @dev Withdraw ether from the smart contract to the specified account. function withdraw(address _to, uint _amount) external onlyController { _to.transfer(_amount); } //// @dev Handle Oraclize query callback and verifiy the provided origin proof. //// @param _queryID Oraclize query ID. //// @param _result query result in JSON format. //// @param _proof origin proof from crypto compare. // solium-disable-next-line mixedcase function __callback(bytes32 _queryID, string _result, bytes _proof) public { // Require that the caller is the Oraclize contract. require(msg.sender == oraclize_cbAddress(), "sender is not oraclize"); // Use the query ID to find the matching token address. address _token = _queryToToken[_queryID]; require(_token != address(0), "queryID matches to address 0"); // Get the corresponding token object. Token storage token = tokens[_token]; bool valid; uint timestamp; (valid, timestamp) = _verifyProof(_result, _proof, APIPublicKey, token.lastUpdate); // Require that the proof is valid. if (valid) { // Parse the JSON result to get the rate in wei. token.rate = _parseIntScientificWei(parseRate(_result)); // Set the update time of the token rate. token.lastUpdate = timestamp; // Remove query from the list. delete _queryToToken[_queryID]; // Emit the rate update event. emit UpdatedTokenRate(msg.sender, _token, token.rate); } } /// @dev Re-usable helper function that performs the Oraclize Query. //// @param _gasLimit the gas limit is passed, this is used for the Oraclize callback function _updateTokenRates(uint _gasLimit) private { // Check if there are any existing tokens. if (_tokenAddresses.length == 0) { // Emit a query failure event. emit FailedUpdateRequest("no tokens"); // Check if the contract has enough Ether to pay for the query. } else if (oraclize_getPrice("URL") * _tokenAddresses.length > address(this).balance) { // Emit a query failure event. emit FailedUpdateRequest("insufficient balance"); } else { // Set up the cryptocompare API query strings. strings.slice memory apiPrefix = "https://min-api.cryptocompare.com/data/price?fsym=".toSlice(); strings.slice memory apiSuffix = "&tsyms=ETH&sign=true".toSlice(); // Create a new oraclize query for each supported token. for (uint i = 0; i < _tokenAddresses.length; i++) { // Store the token symbol used in the query. strings.slice memory symbol = tokens[_tokenAddresses[i]].symbol.toSlice(); // Create a new oraclize query from the component strings. bytes32 queryID = oraclize_query("URL", apiPrefix.concat(symbol).toSlice().concat(apiSuffix), _gasLimit); // Store the query ID together with the associated token address. _queryToToken[queryID] = _tokenAddresses[i]; // Emit the query success event. emit RequestedUpdate(symbol.toString()); } } } /// @dev Verify the origin proof returned by the cryptocompare API. /// @param _result query result in JSON format. /// @param _proof origin proof from cryptocompare. /// @param _publicKey cryptocompare public key. /// @param _lastUpdate timestamp of the last time the requested token was updated. function _verifyProof(string _result, bytes _proof, bytes _publicKey, uint _lastUpdate) private returns (bool, uint) { //expecting fixed length proofs if (_proof.length != PROOF_LEN) revert("invalid proof length"); //proof should be 65 bytes long: R (32 bytes) + S (32 bytes) + v (1 byte) if (uint(_proof[1]) != ECDSA_SIG_LEN) revert("invalid signature length"); bytes memory signature = new bytes(ECDSA_SIG_LEN); signature = copyBytes(_proof, 2, ECDSA_SIG_LEN, signature, 0); // Extract the headers, big endian encoding of headers length if (uint(_proof[ENCODING_BYTES + ECDSA_SIG_LEN]) * MAX_BYTE_SIZE + uint(_proof[ENCODING_BYTES + ECDSA_SIG_LEN + 1]) != HEADERS_LEN) revert("invalid headers length"); bytes memory headers = new bytes(HEADERS_LEN); headers = copyBytes(_proof, 2*ENCODING_BYTES + ECDSA_SIG_LEN, HEADERS_LEN, headers, 0); // Check if the signature is valid and if the signer address is matching. if (!_verifySignature(headers, signature, _publicKey)) { revert("invalid signature"); } // Check if the date is valid. bytes memory dateHeader = new bytes(20); //keep only the relevant string(e.g. "16 Nov 2018 16:22:18") dateHeader = copyBytes(headers, 11, 20, dateHeader, 0); bool dateValid; uint timestamp; (dateValid, timestamp) = _verifyDate(string(dateHeader), _lastUpdate); // Check whether the date returned is valid or not if (!dateValid) revert("invalid date"); // Check if the signed digest hash matches the result hash. bytes memory digest = new bytes(DIGEST_BASE64_LEN); digest = copyBytes(headers, DIGEST_OFFSET, DIGEST_BASE64_LEN, digest, 0); if (keccak256(abi.encodePacked(sha256(abi.encodePacked(_result)))) != keccak256(_base64decode(digest))) revert("result hash not matching"); emit VerifiedProof(_publicKey, _result); return (true, timestamp); } /// @dev Verify the HTTP headers and the signature /// @param _headers HTTP headers provided by the cryptocompare api /// @param _signature signature provided by the cryptocompare api /// @param _publicKey cryptocompare public key. function _verifySignature(bytes _headers, bytes _signature, bytes _publicKey) private returns (bool) { address signer; bool signatureOK; // Checks if the signature is valid by hashing the headers (signatureOK, signer) = ecrecovery(sha256(_headers), _signature); return signatureOK && signer == address(keccak256(_publicKey)); } /// @dev Verify the signed HTTP date header. /// @param _dateHeader extracted date string e.g. Wed, 12 Sep 2018 15:18:14 GMT. /// @param _lastUpdate timestamp of the last time the requested token was updated. function _verifyDate(string _dateHeader, uint _lastUpdate) private pure returns (bool, uint) { //called by verifyProof(), _dateHeader is always a string of length = 20 assert(abi.encodePacked(_dateHeader).length == 20); //Split the date string and get individual date components. strings.slice memory date = _dateHeader.toSlice(); strings.slice memory timeDelimiter = ":".toSlice(); strings.slice memory dateDelimiter = " ".toSlice(); uint day = _parseIntScientific(date.split(dateDelimiter).toString()); require(day > 0 && day < 32, "day error"); uint month = _monthToNumber(date.split(dateDelimiter).toString()); require(month > 0 && month < 13, "month error"); uint year = _parseIntScientific(date.split(dateDelimiter).toString()); require(year > 2017 && year < 3000, "year error"); uint hour = _parseIntScientific(date.split(timeDelimiter).toString()); require(hour < 25, "hour error"); uint minute = _parseIntScientific(date.split(timeDelimiter).toString()); require(minute < 60, "minute error"); uint second = _parseIntScientific(date.split(timeDelimiter).toString()); require(second < 60, "second error"); uint timestamp = year * (10 ** 10) + month * (10 ** 8) + day * (10 ** 6) + hour * (10 ** 4) + minute * (10 ** 2) + second; return (timestamp > _lastUpdate, timestamp); } }
this returns a 'false' to imply that a card is not protected
return (false, 0);
991,103
[ 1, 2211, 1135, 279, 296, 5743, 11, 358, 709, 1283, 716, 279, 5270, 353, 486, 4750, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 327, 261, 5743, 16, 374, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; import "./util/WithoutDefaultFunction.sol"; contract PryzeSweepstakes { string public name; string public sponsorName; string public sponsorTermsUrl; string public contactInformation; string public prizeDescription; address public sponsor; address public factoryOwner; uint public startTime; uint public endTime; uint public winnerIndex; bool isActive = false; bytes32 hashOfEntries; uint public totalEntries; // save reject reason for entrant at index mapping(uint => bytes32) public rejectReasons; string public winnerTransactionHash; // Events event DecidedWinner(address addr, uint winnerIndex); event AcceptedWinner(address addr, uint winnerIndex, string transactionHash); event RejectedWinner(address addr, uint rejectedWinnerEntryIndex, bytes32 rejectReason); modifier sponsorOnly { require(msg.sender == sponsor); _; } modifier pryzeOnly { require(msg.sender == factoryOwner); _; } modifier pryzeOrSponsorOnly { require(msg.sender == sponsor || msg.sender == factoryOwner); _; } function PryzeSweepstakes( address _sponsor, address _factoryOwner, string _name, string _sponsorName, string _sponsorTermsUrl, string _contactInformation, string _prizeDescription, uint _startTime, uint _endTime ) public { sponsor = _sponsor; factoryOwner = _factoryOwner; name = _name; sponsorName = _sponsorName; sponsorTermsUrl = _sponsorTermsUrl; contactInformation = _contactInformation; prizeDescription = _prizeDescription; startTime = _startTime; endTime = _endTime; isActive = true; } function getName() public constant returns (string) { return name; } function getSponsorName() public constant returns (string) { return sponsorName; } function getSponsorTermsUrl() public constant returns (string) { return sponsorTermsUrl; } function getContactInformation() public constant returns (string) { return contactInformation; } function getPrizeDescription() public constant returns (string) { return prizeDescription; } function getStartTime() public constant returns (uint) { return startTime; } function getEndTime() public constant returns (uint) { return endTime; } function getWinnerIndex() public constant returns (uint) { return winnerIndex; } function getTotalEntries() public constant returns (uint) { return totalEntries; } // Used for state machine for right after data has been set and winner should be selected bool public shouldDecideWinner = false; // Used for state machine after winner has been picked, and sponsor can decide to accept or reject // based on terms bool public shouldAcceptOrRejectWinner = false; // Final state when bool public acceptedWinner = false; // Number entries from the sidechain, and other sidechain information used for randomization and verification uint numberEntries; bytes32 blockHashOfSideChain; uint blockNumberOfSideChain; uint timestampOfSideChain; // Block number that winner pick data is set uint winnerSetDataBlockNumber; // Entry index for winner uint public lastRejectedWinnerEntryIndex; // Entry index for winner uint winnerEntryIndex; function setWinnerPickData(uint _numberEntries, bytes32 _blockHashOfSideChain, uint _blockNumberOfSideChain, uint _timestampOfSideChain) public pryzeOnly { require(!shouldDecideWinner); numberEntries = _numberEntries; blockHashOfSideChain = _blockHashOfSideChain; blockNumberOfSideChain = _blockNumberOfSideChain; timestampOfSideChain = _timestampOfSideChain; winnerSetDataBlockNumber = block.number; shouldDecideWinner = true; } function decideWinner() public pryzeOrSponsorOnly returns(uint) { // Don't let winner be picked if we're the same block as creation because this value is known before the // contract and this function could be called together require(block.number > winnerSetDataBlockNumber); // Make sure we're ready to decide a winner require(shouldDecideWinner && !shouldAcceptOrRejectWinner); uint limit = numberEntries; winnerEntryIndex = uint(sha3( block.blockhash(block.number - 1), blockHashOfSideChain, blockNumberOfSideChain, timestampOfSideChain)) % limit; shouldAcceptOrRejectWinner = true; DecidedWinner(this, winnerEntryIndex); return winnerEntryIndex; } function rejectWinner(bytes32 reason) sponsorOnly { require(shouldAcceptOrRejectWinner && !acceptedWinner); shouldAcceptOrRejectWinner = false; lastRejectedWinnerEntryIndex = winnerEntryIndex; winnerEntryIndex = 0; // save the reject reason rejectReasons[lastRejectedWinnerEntryIndex] = reason; RejectedWinner(this, lastRejectedWinnerEntryIndex, reason); decideWinner(); } function getRejectReasonForIndex (uint index) public returns (bytes32) { return rejectReasons[index]; } function acceptWinner() sponsorOnly { require(shouldAcceptOrRejectWinner && !acceptedWinner); acceptedWinner = true; AcceptedWinner(this, winnerEntryIndex, ""); } // Note: transactionHash is of type string to allow flexibility // for not-ethereum hashes (e.g. bitcoin) function acceptWinner(string transactionHash) sponsorOnly { require(shouldAcceptOrRejectWinner && !acceptedWinner); acceptedWinner = true; winnerTransactionHash = transactionHash; AcceptedWinner(this, winnerEntryIndex, winnerTransactionHash); } function getWinnerEntryIndex() public returns(uint) { return winnerEntryIndex; } }
Block number that winner pick data is set
uint winnerSetDataBlockNumber;
12,788,254
[ 1, 1768, 1300, 716, 5657, 1224, 6002, 501, 353, 444, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5657, 1224, 694, 751, 1768, 1854, 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 ]
./partial_match/1/0x11D6a3aCF149D92e69d58fDA145614Dcc1bf4639/sources/ERC20Token.sol
Set the name for display purposes
name = "LEOSHARES";
9,339,495
[ 1, 694, 326, 508, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 508, 273, 315, 900, 51, 8325, 7031, 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 ]
// contracts/TVL.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155PausableUpgradeable.sol"; import "./TrancheSystem.sol"; /// --------------------------------------- /// @title An NFT for money market rewards /// @author Andreas Bigger <[email protected]> /// @dev ERC1155 NFTs with Chainlink Oracle /// Access to allow pool creators to /// distribute NFT rewards /// --------------------------------------- abstract contract TVL is TrancheSystem, ERC1155PausableUpgradeable { using SafeMathUpgradeable for uint256; // * Adapter Address address internal ADAPTER_CONTRACT_ADDRESS; // * Event to record rug pulls event RugPull(address _from); /// @dev mapping from token id to if it exists mapping(uint256 => bool) public tokenIdExists; /// @dev mapping of amount of tokens per id mapping(uint256 => uint256) public numTokensById; /// @dev maximum tranche token id, token ids must be created sequentially based on id exists uint256 public maxTokenId; /// @dev load metadata api and instantiate ownership /// @param _owner address of the contract owner /// @param _uri base uri for initialization of erc1155 /// @param _adapter_address address of the pool function initialize( address _owner, string memory _uri, address _adapter_address ) public virtual initializer { ADAPTER_CONTRACT_ADDRESS = _adapter_address; __ERC1155_init(_uri); __Ownable_init(); transferOwnership(_owner); } /// @dev function to mint items, only allowed for devs, external /// @param _id token id /// @param _amount: number of tokens /// @param _uri_data: data to be injected into uri /// @return minted id function mintItem( uint256 _id, uint256 _amount, bytes calldata _uri_data ) external onlyOwner nonReentrant aboveZero(_id) returns (uint256) { // * Make sure previous level exists uint256 _prevId = _id.sub(1); if (_prevId > 0) { require( tokenIdExists[_prevId] == true, "Previous token id must exist." ); } // * MINT IT _mint(msg.sender, _id, _amount, _uri_data); // * Set token id stores maxTokenId = _id; tokenIdExists[_id] = true; numTokensById[_id] = _amount; // * Return newly minted token return _id; } /// @dev function to get total amount of tokens over all token ids /// @return uint256 number of total tokens function getTotalNumberTokens() external view returns (uint256) { uint256 totalNum = 0; for (uint256 i = 0; i < maxTokenId; i++) { totalNum = totalNum.add(numTokensById[i]); } return totalNum; } /// @dev overriden function from ERC1155Upgradeable.sol to regulate token transfers /// @param operator token id /// @param from address transferring /// @param to receiving address /// @param data token id data function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { // * Get current user tranche level uint256 user_level = address_to_tranche[from]; // * Get current user tranche from level Tranche memory user_tranche = tranche_map[user_level]; // * Get which ids are available to user uint256[] memory user_ids = user_tranche.ids; for (uint256 id = 0; id < user_ids.length; id++) { uint256 max_amount = tranche_id_amounts[user_level][user_ids[id]]; // * Calculate amount user can withdraw as % of pool TVL uint256 max_allowed = getPoolShare(from, max_amount); require( amounts[id] < max_allowed, "Id amounts must be less than the allowed tranche amounts." ); } super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } /// @notice Must be implemented by children /// @dev function to get the amount of pool share the user has /// @param _from address of the current user /// @param _max_amount the amount of a given token id /// @return uint256 amount of tokens to give to the user function getPoolShare(address _from, uint256 _max_amount) public virtual returns (uint256); /// @dev function to redeem tokens /// @param _ids tranche level /// @param _data data for batch transfer /// @return bool if successful function redeem(uint256[] calldata _ids, bytes calldata _data) external aboveZeroArray(_ids) whenNotPaused() returns (bool) { bool successful = true; // * Get current user tranche level uint256 user_level = address_to_tranche[msg.sender]; // * Get which ids are available to user uint256[] memory user_ids = tranche_map[user_level].ids; // * Batch transfer array uint256[] memory batch_ids = new uint256[](user_ids.length); uint256[] memory batch_amounts = new uint256[](user_ids.length); uint256 counter = 0; // * Iterate over tranche ids and redeem the ones in the input array for (uint256 i = 0; i < user_ids.length; i++) { uint256 user_id = user_ids[i]; for (uint256 x = 0; x < _ids.length; x++) { if (user_id == _ids[x]) { // * If this is an id to redeem, append to amounts for batch transfer batch_ids[counter] = user_id; batch_amounts[counter] = tranche_id_amounts[user_level][ user_id ]; counter++; } } } // * Batch transfer safeBatchTransferFrom( owner(), msg.sender, batch_ids, batch_amounts, _data ); // * Emit redemption event emit TokenRedemption(batch_ids, _data); // * Returns if successful return successful; } /// @dev function set approval for redemption /// @param _user user's address /// @param _approved whether the user is approved to transfer or not function setApproval(address _user, bool _approved) external onlyOwner { // * Set approval setApprovalForAll(_user, _approved); } /// -------------------------------------------------------- /// Pausible Function Implementations /// -------------------------------------------------------- /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public whenNotPaused onlyOwner { _pause(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public whenPaused onlyOwner { _unpause(); } /// @dev disables any token flow by pausing the contract and claws back any to contract owner function rugPull() external onlyOwner { // * Pause the contract and all token transfers pause(); // * Claw back all tokens _claw(); // * Emit event emit RugPull(msg.sender); } // @dev internal function to claw back all tokens to specific admin address function _claw() public onlyOwner { // TODO: Implement } }
* Set token id stores
maxTokenId = _id;
5,458,729
[ 1, 694, 1147, 612, 9064, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 1345, 548, 273, 389, 350, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xb0c6BDb00E4BF851fDD7563A5067A1d3A9Dbc3Bc/sources/PalaCoin.sol
uint never less than 0. The negative number will become to a big positive number
function transferAndFreezing(address _to, uint256 _value, uint256 freeze_amount, uint end_stamp, uint8 freezing_type) auth stoppable public returns (bool) { require(_value <= c_totalSupply); require(freeze_amount <= _value); transfer(_to, _value); setFreezing(_to, end_stamp, freeze_amount, freezing_type); return true; }
5,315,964
[ 1, 11890, 5903, 5242, 2353, 374, 18, 1021, 6092, 1300, 903, 12561, 358, 279, 5446, 6895, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1876, 9194, 94, 310, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 16, 2254, 5034, 16684, 67, 8949, 16, 2254, 679, 67, 14317, 16, 2254, 28, 4843, 94, 310, 67, 723, 13, 1357, 2132, 19586, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 1132, 1648, 276, 67, 4963, 3088, 1283, 1769, 203, 3639, 2583, 12, 29631, 67, 8949, 1648, 389, 1132, 1769, 203, 203, 3639, 7412, 24899, 869, 16, 389, 1132, 1769, 203, 3639, 444, 9194, 94, 310, 24899, 869, 16, 679, 67, 14317, 16, 16684, 67, 8949, 16, 4843, 94, 310, 67, 723, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: contracts/GeoHunter.sol pragma solidity ^0.5.0; /// @title ETHdenver 2019 Project: GeoHunter /// @dev Contract Project will inherit the contracts Ownable and Pausable from the OpenZeppelin library /// @dev Pausable is a circuit breaker which blocks all contract functions expect withdrawal by the owner contract GeoHunter is Ownable, Pausable { // Global variables uint32 public totalTags; uint32 public totalUsers; uint32 public totalScans; // Events event balanceNowUpdated(uint256 _newBalance); event tagNowRegistered(uint32 _tagIndex, string _tagUid, string _ipfsHash, string _lat, string _long); event userNowRegistered(string _userDid, string _username); event tagNowScanned(string userDid, string username, string tagUid, uint timestamp); // Structs & Mappings struct Tag { string Uid; string ipfsHash; // Could be a hash of a picture of the tag location string lat; string long; } mapping (string => uint32) private tagIndex; // 0 returned means tag UID is unregistered mapping (uint32 => Tag) public tagList; // Since index 0 means tag UID is unregistered, index 1 to 5 will be the five game tags struct User { string userDid; string username; uint8 progress; uint startTime; uint endTime; } mapping (string => uint32) private userIndex; // 0 returned means user DID is unregistered mapping (uint32 => User) public userList; // Since index 0 means user DID is unregistered, 1st user is index 1 struct Scan { string userDid; string username; string tagUid; uint timestamp; } mapping (uint32 => Scan) public scanList; /// @dev Constructor /// @dev Initialize totals, and hardcode game with the details of 5 tags constructor() public { totalTags = 5; // Five tags are hardcoded into the constructor totalUsers = 3; // Three test users are hardcoded into the constructor totalScans = 0; // Hardcoded details for a test user, index 1, who is registered but hasn't started yet userIndex["did:example:1123456789abcdefghi"] = 1; userList[1].userDid = "did:example:1123456789abcdefghi"; userList[1].username = "Test User 1"; userList[1].progress = 0; userList[1].startTime = 0; userList[1].endTime = 0; // Hardcoded details for a test user, index 2, who is registered and almost finished the challenge userIndex["did:example:2123456789abcdefghi"] = 2; userList[2].userDid = "did:example:2123456789abcdefghi"; userList[2].username = "Test User 2"; userList[2].progress = 4; userList[2].startTime = 1550370000; userList[2].endTime = 0; // Hardcoded details for a test user, index 3, who is registered and has completed the challenge userIndex["did:example:3123456789abcdefghi"] = 3; userList[3].userDid = "did:example:3123456789abcdefghi"; userList[3].username = "Test User 3"; userList[3].progress = 5; userList[3].startTime = 1550370000; userList[3].endTime = 1550371000; // Hardcoded details for Tag index 1 (tag UID, IPFS hash, and location latitude and longitude) tagIndex["16199909d0b5fd"] = 1; // Replace with actual UID tagList[1].Uid = "16199909d0b5fd"; // Replace with actual UID tagList[1].ipfsHash = "1mWWQSuPMS6aXCbZKpEjPHPUZN2NjB3YrhJTHsV4X3vb2t"; // Replace with actual IPFS hash tagList[1].lat = ""; tagList[1].long = ""; // Hardcoded details for Tag index 2 (tag UID, IPFS hash, and location latitude and longitude) tagIndex["26199909d0b5fd"] = 2; // Replace with actual UID tagList[2].Uid = "26199909d0b5fd"; // Replace with actual UID tagList[2].ipfsHash = "2mWWQSuPMS6aXCbZKpEjPHPUZN2NjB3YrhJTHsV4X3vb2t"; // Replace with actual IPFS hash tagList[2].lat = ""; tagList[2].long = ""; // Hardcoded details for Tag index 3 (tag UID, IPFS hash, and location latitude and longitude) tagIndex["36199909d0b5fd"] = 3; // Replace with actual UID tagList[3].Uid = "36199909d0b5fd"; // Replace with actual UID tagList[3].ipfsHash = "3mWWQSuPMS6aXCbZKpEjPHPUZN2NjB3YrhJTHsV4X3vb2t"; // Replace with actual IPFS hash tagList[3].lat = ""; tagList[3].long = ""; // Hardcoded details for Tag index 4 (tag UID, IPFS hash, and location latitude and longitude) tagIndex["46199909d0b5fd"] = 4; // Replace with actual UID tagList[4].Uid = "46199909d0b5fd"; // Replace with actual UID tagList[4].ipfsHash = "4mWWQSuPMS6aXCbZKpEjPHPUZN2NjB3YrhJTHsV4X3vb2t"; // Replace with actual IPFS hash tagList[4].lat = ""; tagList[4].long = ""; // Hardcoded details for Tag index 5 (tag UID, IPFS hash, and location latitude and longitude) tagIndex["56199909d0b5fd"] = 5; // Replace with actual UID tagList[5].Uid = "56199909d0b5fd"; // Replace with actual UID tagList[5].ipfsHash = "5mWWQSuPMS6aXCbZKpEjPHPUZN2NjB3YrhJTHsV4X3vb2t"; // Replace with actual IPFS hash tagList[5].lat = ""; tagList[5].long = ""; } /// @dev Fallback function function () external payable { } /// @dev The owner can add ETH to the contract when the contract is not paused function addBalance() public payable onlyOwner whenNotPaused { emit balanceNowUpdated(address(this).balance); } /// @dev The owner can withdraw ETH from the contract when the contract is not paused /// @param amount Value to be withdrawn in wei function withdrawBalance (uint256 amount) public onlyOwner whenNotPaused { msg.sender.transfer(amount); emit balanceNowUpdated(address(this).balance); } /// @dev Register tags with a particular index number and IPFS hash /// @param _tagIndex Desired Tag Index - will overwrite previous tag registered to that index if existing /// An index of 0 will create a new tag and increment the total tag count /// @param _tagUid Tag UID code /// @param _ipfsHash IPFS hash associated with the tag (could be a hash of a picture of the tag location) /// @param _lat Location (latitude) of tag /// @param _long Location (longitude) of tag function registerTag( uint32 _tagIndex, string memory _tagUid, string memory _ipfsHash, string memory _lat, string memory _long) public onlyOwner returns (bool) { require(_tagIndex <= totalTags, "Tag index cannot be greater than the current number of tags"); uint32 newTagIndex; if (_tagIndex == 0) { totalTags++; newTagIndex = totalTags; tagIndex[_tagUid] = newTagIndex; } else { newTagIndex = _tagIndex; } tagList[newTagIndex].Uid = _tagUid; tagList[newTagIndex].ipfsHash = _ipfsHash; tagList[newTagIndex].lat = _lat; tagList[newTagIndex].long = _long; emit tagNowRegistered(_tagIndex, _tagUid, _ipfsHash, _lat, _long); return true; } /// @dev Register users with a unique index number and associated username /// @param _userDid User's uPort DID code /// @param _username User's uPort username function registerUser( string memory _userDid, string memory _username) public returns (bool) { require(userIndex[_userDid] == 0, "User already registered"); totalUsers++; userIndex[_userDid] = totalUsers; userList[userIndex[_userDid]].userDid = _userDid; userList[userIndex[_userDid]].username = _username; userList[userIndex[_userDid]].progress = 0; userList[userIndex[_userDid]].startTime = 0; userList[userIndex[_userDid]].endTime = 0; emit userNowRegistered(_userDid, _username); return true; } /// @dev Record the scanning of tags /// @param _userDid User's uPort DID code /// @param _username User's uPort username /// @param _tagUid Tag UID code function scanTag( string memory _userDid, string memory _username, string memory _tagUid) public returns (bool) { if (userIndex[_userDid] == 0) { require(registerUser(_userDid, _username), "User already registered"); // Register user if not already registered } string memory nextTagUid = tagList[userList[userIndex[_userDid]].progress + 1].Uid; if (keccak256(abi.encode(_tagUid)) == keccak256(abi.encode(nextTagUid))) { userList[userIndex[_userDid]].progress++; // Progress user if they have scanned the next tag if (userList[userIndex[_userDid]].progress == 1) { userList[userIndex[_userDid]].startTime == block.timestamp; // If tag is index 1 then record user's start time } if (userList[userIndex[_userDid]].progress == 5) { userList[userIndex[_userDid]].endTime == block.timestamp; // If tag is index 5 then record user's end time } } totalScans++; scanList[totalScans].userDid = _userDid; scanList[totalScans].username = _username; scanList[totalScans].tagUid = _tagUid; scanList[totalScans].timestamp = block.timestamp; emit tagNowScanned(_userDid, _username, _tagUid, block.timestamp); return true; } /// @dev Get the index and Uid for the next tag the user requires /// @param _userDid User's uPort DID code /// @param _nextTagIndex The index number for the next tag the user requires (1 to 5; 6 means user is done) /// @param _nextTagUid Tag UID code for the next tag the user requires function nextTagRequired(string memory _userDid) public view returns ( uint32 _nextTagIndex, string memory _nextTagUid, bool _success) { require(userIndex[_userDid] > 0, "User not registered"); _nextTagIndex = userList[userIndex[_userDid]].progress + 1; _nextTagUid = tagList[_nextTagIndex].Uid; _success = true; } /// @dev Returns the current total number of tags registered /// @param _totalTags Current total number of tags registered function getTotalTags() public view returns (uint32 _totalTags) { _totalTags = totalTags; } /// @dev Returns the current total number of users registered /// @param _totalUsers Current total number of users registered function getTotalUsers() public view returns (uint32 _totalUsers) { _totalUsers = totalUsers; } /// @dev Returns the current total number of scans /// @param _totalScans Current total number of scans function getTotalScans() public view returns (uint32 _totalScans) { _totalScans = totalScans; } /// @dev Returns the requested user data by index function getUser(uint32 _userIndex) public view returns ( string memory _userDid, string memory _username, uint8 _progress, uint _startTime, uint _endTime) { _userDid = userList[_userIndex].userDid; _username = userList[_userIndex].username; _progress = userList[_userIndex].progress; _startTime = userList[_userIndex].startTime; _endTime = userList[_userIndex].endTime; } /// @dev Returns the requested tag data by index function getTag(uint32 _tagIndex) public view returns ( string memory _Uid, string memory _ipfsHash, string memory _lat, string memory _long) { _Uid = tagList[_tagIndex].Uid; _ipfsHash = tagList[_tagIndex].ipfsHash; _lat = tagList[_tagIndex].lat; _long = tagList[_tagIndex].long; } /// @dev Returns the requested scan data by index function getScan(uint32 _scanIndex) public view returns ( string memory _userDid, string memory _username, string memory _tagUid, uint _timestamp) { _userDid = scanList[_scanIndex].userDid; _username = scanList[_scanIndex].username; _tagUid = scanList[_scanIndex].tagUid; _timestamp = scanList[_scanIndex].timestamp; } }
Replace with actual IPFS hash
tagList[2].ipfsHash = "2mWWQSuPMS6aXCbZKpEjPHPUZN2NjB3YrhJTHsV4X3vb2t";
6,410,335
[ 1, 5729, 598, 3214, 2971, 4931, 1651, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1047, 682, 63, 22, 8009, 625, 2556, 2310, 273, 315, 22, 81, 19989, 53, 17072, 52, 3537, 26, 69, 60, 15237, 62, 47, 84, 41, 78, 7159, 57, 62, 50, 22, 50, 78, 38, 23, 61, 30138, 46, 2455, 87, 58, 24, 60, 23, 90, 70, 22, 88, 14432, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./Rollup.sol"; import "./facets/IRollupFacets.sol"; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/IMessageProvider.sol"; import "./INode.sol"; import "../libraries/Cloneable.sol"; contract RollupEventBridge is IMessageProvider, Cloneable { uint8 internal constant INITIALIZATION_MSG_TYPE = 11; uint8 internal constant ROLLUP_PROTOCOL_EVENT_TYPE = 8; uint8 internal constant CREATE_NODE_EVENT = 0; uint8 internal constant CONFIRM_NODE_EVENT = 1; uint8 internal constant REJECT_NODE_EVENT = 2; uint8 internal constant STAKE_CREATED_EVENT = 3; IBridge bridge; address rollup; modifier onlyRollup() { require(msg.sender == rollup, "ONLY_ROLLUP"); _; } function initialize(address _bridge, address _rollup) external { require(rollup == address(0), "ALREADY_INIT"); bridge = IBridge(_bridge); rollup = _rollup; } function rollupInitialized( uint256 confirmPeriodBlocks, uint256 avmGasSpeedLimitPerBlock, address owner, bytes calldata extraConfig ) external onlyRollup { bytes memory initMsg = abi.encodePacked( keccak256("ChallengePeriodEthBlocks"), confirmPeriodBlocks, keccak256("SpeedLimitPerSecond"), avmGasSpeedLimitPerBlock / 100, // convert avm gas to arbgas keccak256("ChainOwner"), uint256(uint160(bytes20(owner))), extraConfig ); uint256 num = bridge.deliverMessageToInbox( INITIALIZATION_MSG_TYPE, address(0), keccak256(initMsg) ); emit InboxMessageDelivered(num, initMsg); } function nodeCreated( uint256 nodeNum, uint256 prev, uint256 deadline, address asserter ) external onlyRollup { deliverToBridge( abi.encodePacked( CREATE_NODE_EVENT, nodeNum, prev, block.number, deadline, uint256(uint160(bytes20(asserter))) ) ); } function nodeConfirmed(uint256 nodeNum) external onlyRollup { deliverToBridge(abi.encodePacked(CONFIRM_NODE_EVENT, nodeNum)); } function nodeRejected(uint256 nodeNum) external onlyRollup { deliverToBridge(abi.encodePacked(REJECT_NODE_EVENT, nodeNum)); } function stakeCreated(address staker, uint256 nodeNum) external onlyRollup { deliverToBridge( abi.encodePacked( STAKE_CREATED_EVENT, uint256(uint160(bytes20(staker))), nodeNum, block.number ) ); } function deliverToBridge(bytes memory message) private { emit InboxMessageDelivered( bridge.deliverMessageToInbox( ROLLUP_PROTOCOL_EVENT_TYPE, msg.sender, keccak256(message) ), message ); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/proxy/Proxy.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./RollupEventBridge.sol"; import "./RollupCore.sol"; import "./RollupLib.sol"; import "./INode.sol"; import "./INodeFactory.sol"; import "../challenge/IChallenge.sol"; import "../challenge/IChallengeFactory.sol"; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/IOutbox.sol"; import "../bridge/Messages.sol"; import "../libraries/ProxyUtil.sol"; import "../libraries/Cloneable.sol"; import "./facets/IRollupFacets.sol"; abstract contract RollupBase is Cloneable, RollupCore, Pausable { // Rollup Config uint256 public confirmPeriodBlocks; uint256 public extraChallengeTimeBlocks; uint256 public avmGasSpeedLimitPerBlock; uint256 public baseStake; // Bridge is an IInbox and IOutbox IBridge public delayedBridge; ISequencerInbox public sequencerBridge; IOutbox public outbox; RollupEventBridge public rollupEventBridge; IChallengeFactory public challengeFactory; INodeFactory public nodeFactory; address public owner; address public stakeToken; uint256 public minimumAssertionPeriod; uint256 public STORAGE_GAP_1; uint256 public STORAGE_GAP_2; uint256 public challengeExecutionBisectionDegree; address[] internal facets; mapping(address => bool) isValidator; /// @notice DEPRECATED -- this method is deprecated but still mantained for backward compatibility /// @dev this actually returns the avmGasSpeedLimitPerBlock /// @return this actually returns the avmGasSpeedLimitPerBlock function arbGasSpeedLimitPerBlock() external view returns (uint256) { return avmGasSpeedLimitPerBlock; } } contract Rollup is Proxy, RollupBase { using Address for address; constructor(uint256 _confirmPeriodBlocks) public Cloneable() Pausable() { // constructor is used so logic contract can't be init'ed confirmPeriodBlocks = _confirmPeriodBlocks; require(isInit(), "CONSTRUCTOR_NOT_INIT"); } function isInit() internal view returns (bool) { return confirmPeriodBlocks != 0; } // _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, avmGasSpeedLimitPerBlock, baseStake ] // connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory] function initialize( bytes32 _machineHash, uint256[4] calldata _rollupParams, address _stakeToken, address _owner, bytes calldata _extraConfig, address[6] calldata connectedContracts, address[2] calldata _facets, uint256[2] calldata sequencerInboxParams ) public { require(!isInit(), "ALREADY_INIT"); // calls initialize method in user facet require(_facets[0].isContract(), "FACET_0_NOT_CONTRACT"); require(_facets[1].isContract(), "FACET_1_NOT_CONTRACT"); (bool success, ) = _facets[1].delegatecall( abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken) ); require(success, "FAIL_INIT_FACET"); delayedBridge = IBridge(connectedContracts[0]); sequencerBridge = ISequencerInbox(connectedContracts[1]); outbox = IOutbox(connectedContracts[2]); delayedBridge.setOutbox(connectedContracts[2], true); rollupEventBridge = RollupEventBridge(connectedContracts[3]); delayedBridge.setInbox(connectedContracts[3], true); rollupEventBridge.rollupInitialized( _rollupParams[0], _rollupParams[2], _owner, _extraConfig ); challengeFactory = IChallengeFactory(connectedContracts[4]); nodeFactory = INodeFactory(connectedContracts[5]); INode node = createInitialNode(_machineHash); initializeCore(node); confirmPeriodBlocks = _rollupParams[0]; extraChallengeTimeBlocks = _rollupParams[1]; avmGasSpeedLimitPerBlock = _rollupParams[2]; baseStake = _rollupParams[3]; owner = _owner; // A little over 15 minutes minimumAssertionPeriod = 75; challengeExecutionBisectionDegree = 400; sequencerBridge.setMaxDelay(sequencerInboxParams[0], sequencerInboxParams[1]); // facets[0] == admin, facets[1] == user facets = _facets; emit RollupCreated(_machineHash); require(isInit(), "INITIALIZE_NOT_INIT"); } function postUpgradeInit() external { // it is assumed the rollup contract is behind a Proxy controlled by a proxy admin // this function can only be called by the proxy admin contract address proxyAdmin = ProxyUtil.getProxyAdmin(); require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN"); // this upgrade moves the delay blocks and seconds tracking to the sequencer inbox // because of that we need to update the admin facet logic to allow the owner to set // these values in the sequencer inbox STORAGE_GAP_1 = 0; STORAGE_GAP_2 = 0; } function createInitialNode(bytes32 _machineHash) private returns (INode) { bytes32 state = RollupLib.stateHash( RollupLib.ExecutionState( 0, // total gas used _machineHash, 0, // inbox count 0, // send count 0, // log count 0, // send acc 0, // log acc block.number, // block proposed 1 // Initialization message already in inbox ) ); return INode( nodeFactory.createNode( state, 0, // challenge hash (not challengeable) 0, // confirm data 0, // prev node block.number // deadline block (not challengeable) ) ); } /** * This contract uses a dispatch pattern from EIP-2535: Diamonds * together with Open Zeppelin's proxy */ function getFacets() external view returns (address, address) { return (getAdminFacet(), getUserFacet()); } function getAdminFacet() public view returns (address) { return facets[0]; } function getUserFacet() public view returns (address) { return facets[1]; } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual override returns (address) { require(msg.data.length >= 4, "NO_FUNC_SIG"); address rollupOwner = owner; // if there is an owner and it is the sender, delegate to admin facet address target = rollupOwner != address(0) && rollupOwner == msg.sender ? getAdminFacet() : getUserFacet(); require(target.isContract(), "TARGET_NOT_CONTRACT"); return target; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../INode.sol"; import "../../bridge/interfaces/IOutbox.sol"; interface IRollupUser { function initialize(address _stakeToken) external; function completeChallenge(address winningStaker, address losingStaker) external; function returnOldDeposit(address stakerAddress) external; function requireUnresolved(uint256 nodeNum) external view; function requireUnresolvedExists() external view; function countStakedZombies(INode node) external view returns (uint256); } interface IRollupAdmin { event OwnerFunctionCalled(uint256 indexed id); /** * @notice Add a contract authorized to put messages into this rollup's inbox * @param _outbox Outbox contract to add */ function setOutbox(IOutbox _outbox) external; /** * @notice Disable an old outbox from interacting with the bridge * @param _outbox Outbox contract to remove */ function removeOldOutbox(address _outbox) external; /** * @notice Enable or disable an inbox contract * @param _inbox Inbox contract to add or remove * @param _enabled New status of inbox */ function setInbox(address _inbox, bool _enabled) external; /** * @notice Pause interaction with the rollup contract */ function pause() external; /** * @notice Resume interaction with the rollup contract */ function resume() external; /** * @notice Set the addresses of rollup logic facets called * @param newAdminFacet address of logic that owner of rollup calls * @param newUserFacet ddress of logic that user of rollup calls */ function setFacets(address newAdminFacet, address newUserFacet) external; /** * @notice Set the addresses of the validator whitelist * @dev It is expected that both arrays are same length, and validator at * position i corresponds to the value at position i * @param _validator addresses to set in the whitelist * @param _val value to set in the whitelist for corresponding address */ function setValidator(address[] memory _validator, bool[] memory _val) external; /** * @notice Set a new owner address for the rollup * @param newOwner address of new rollup owner */ function setOwner(address newOwner) external; /** * @notice Set minimum assertion period for the rollup * @param newPeriod new minimum period for assertions */ function setMinimumAssertionPeriod(uint256 newPeriod) external; /** * @notice Set number of blocks until a node is considered confirmed * @param newConfirmPeriod new number of blocks until a node is confirmed */ function setConfirmPeriodBlocks(uint256 newConfirmPeriod) external; /** * @notice Set number of extra blocks after a challenge * @param newExtraTimeBlocks new number of blocks */ function setExtraChallengeTimeBlocks(uint256 newExtraTimeBlocks) external; /** * @notice Set speed limit per block * @param newAvmGasSpeedLimitPerBlock maximum avmgas to be used per block */ function setAvmGasSpeedLimitPerBlock(uint256 newAvmGasSpeedLimitPerBlock) external; /** * @notice Set base stake required for an assertion * @param newBaseStake maximum avmgas to be used per block */ function setBaseStake(uint256 newBaseStake) external; /** * @notice Set the token used for stake, where address(0) == eth * @dev Before changing the base stake token, you might need to change the * implementation of the Rollup User facet! * @param newStakeToken address of token used for staking */ function setStakeToken(address newStakeToken) external; /** * @notice Set max delay for sequencer inbox * @param newSequencerInboxMaxDelayBlocks max number of blocks * @param newSequencerInboxMaxDelaySeconds max number of seconds */ function setSequencerInboxMaxDelay( uint256 newSequencerInboxMaxDelayBlocks, uint256 newSequencerInboxMaxDelaySeconds ) external; /** * @notice Set execution bisection degree * @param newChallengeExecutionBisectionDegree execution bisection degree */ function setChallengeExecutionBisectionDegree(uint256 newChallengeExecutionBisectionDegree) external; /** * @notice Updates a whitelist address for its consumers * @dev setting the newWhitelist to address(0) disables it for consumers * @param whitelist old whitelist to be deprecated * @param newWhitelist new whitelist to be used * @param targets whitelist consumers to be triggered */ function updateWhitelistConsumers( address whitelist, address newWhitelist, address[] memory targets ) external; /** * @notice Updates a whitelist's entries * @dev user at position i will be assigned value i * @param whitelist whitelist to be updated * @param user users to be updated in the whitelist * @param val if user is or not allowed in the whitelist */ function setWhitelistEntries( address whitelist, address[] memory user, bool[] memory val ) external; /** * @notice Updates whether an address is a sequencer at the sequencer inbox * @param newSequencer address to be modified * @param isSequencer whether this address should be authorized as a sequencer */ function setIsSequencer(address newSequencer, bool isSequencer) external; /** * @notice Upgrades the implementation of a beacon controlled by the rollup * @param beacon address of beacon to be upgraded * @param newImplementation new address of implementation */ function upgradeBeacon(address beacon, address newImplementation) external; function forceResolveChallenge(address[] memory stackerA, address[] memory stackerB) external; function forceRefundStaker(address[] memory stacker) external; function forceCreateNode( bytes32 expectedNodeHash, bytes32[3][2] calldata assertionBytes32Fields, uint256[4][2] calldata assertionIntFields, bytes calldata sequencerBatchProof, uint256 beforeProposedBlock, uint256 beforeInboxMaxCount, uint256 prevNode ) external; function forceConfirmNode( uint256 nodeNum, bytes32 beforeSendAcc, bytes calldata sendsData, uint256[] calldata sendLengths, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount ) external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface IBridge { event MessageDelivered( uint256 indexed messageIndex, bytes32 indexed beforeInboxAcc, address inbox, uint8 kind, address sender, bytes32 messageDataHash ); event BridgeCallTriggered( address indexed outbox, address indexed destAddr, uint256 amount, bytes data ); event InboxToggle(address indexed inbox, bool enabled); event OutboxToggle(address indexed outbox, bool enabled); function deliverMessageToInbox( uint8 kind, address sender, bytes32 messageDataHash ) external payable returns (uint256); function executeCall( address destAddr, uint256 amount, bytes calldata data ) external returns (bool success, bytes memory returnData); // These are only callable by the admin function setInbox(address inbox, bool enabled) external; function setOutbox(address inbox, bool enabled) external; // View functions function activeOutbox() external view returns (address); function allowedInboxes(address inbox) external view returns (bool); function allowedOutboxes(address outbox) external view returns (bool); function inboxAccs(uint256 index) external view returns (bytes32); function messageCount() external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface IMessageProvider { event InboxMessageDelivered(uint256 indexed messageNum, bytes data); event InboxMessageDeliveredFromOrigin(uint256 indexed messageNum); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface INode { function initialize( address _rollup, bytes32 _stateHash, bytes32 _challengeHash, bytes32 _confirmData, uint256 _prev, uint256 _deadlineBlock ) external; function destroy() external; function addStaker(address staker) external returns (uint256); function removeStaker(address staker) external; function childCreated(uint256) external; function newChildConfirmDeadline(uint256 deadline) external; function stateHash() external view returns (bytes32); function challengeHash() external view returns (bytes32); function confirmData() external view returns (bytes32); function prev() external view returns (uint256); function deadlineBlock() external view returns (uint256); function noChildConfirmedBeforeBlock() external view returns (uint256); function stakerCount() external view returns (uint256); function stakers(address staker) external view returns (bool); function firstChildBlock() external view returns (uint256); function latestChildNumber() external view returns (uint256); function requirePastDeadline() external view; function requirePastChildConfirmDeadline() external view; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./ICloneable.sol"; contract Cloneable is ICloneable { string private constant NOT_CLONE = "NOT_CLONE"; bool private isMasterCopy; constructor() public { isMasterCopy = true; } function isMaster() external view override returns (bool) { return isMasterCopy; } function safeSelfDestruct(address payable dest) internal { require(!isMasterCopy, NOT_CLONE); selfdestruct(dest); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./INode.sol"; import "./IRollupCore.sol"; import "./RollupLib.sol"; import "./INodeFactory.sol"; import "./RollupEventBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract RollupCore is IRollupCore { using SafeMath for uint256; // Stakers become Zombies after losing a challenge struct Zombie { address stakerAddress; uint256 latestStakedNode; } struct Staker { uint256 index; uint256 latestStakedNode; uint256 amountStaked; // currentChallenge is 0 if staker is not in a challenge address currentChallenge; bool isStaked; } uint256 private _latestConfirmed; uint256 private _firstUnresolvedNode; uint256 private _latestNodeCreated; uint256 private _lastStakeBlock; mapping(uint256 => INode) private _nodes; mapping(uint256 => bytes32) private _nodeHashes; address payable[] private _stakerList; mapping(address => Staker) public override _stakerMap; Zombie[] private _zombies; mapping(address => uint256) private _withdrawableFunds; /** * @notice Get the address of the Node contract for the given node * @param nodeNum Index of the node * @return Address of the Node contract */ function getNode(uint256 nodeNum) public view override returns (INode) { return _nodes[nodeNum]; } /** * @notice Get the address of the staker at the given index * @param stakerNum Index of the staker * @return Address of the staker */ function getStakerAddress(uint256 stakerNum) external view override returns (address) { return _stakerList[stakerNum]; } /** * @notice Check whether the given staker is staked * @param staker Staker address to check * @return True or False for whether the staker was staked */ function isStaked(address staker) public view override returns (bool) { return _stakerMap[staker].isStaked; } /** * @notice Get the latest staked node of the given staker * @param staker Staker address to lookup * @return Latest node staked of the staker */ function latestStakedNode(address staker) public view override returns (uint256) { return _stakerMap[staker].latestStakedNode; } /** * @notice Get the current challenge of the given staker * @param staker Staker address to lookup * @return Current challenge of the staker */ function currentChallenge(address staker) public view override returns (address) { return _stakerMap[staker].currentChallenge; } /** * @notice Get the amount staked of the given staker * @param staker Staker address to lookup * @return Amount staked of the staker */ function amountStaked(address staker) public view override returns (uint256) { return _stakerMap[staker].amountStaked; } /** * @notice Get the original staker address of the zombie at the given index * @param zombieNum Index of the zombie to lookup * @return Original staker address of the zombie */ function zombieAddress(uint256 zombieNum) public view override returns (address) { return _zombies[zombieNum].stakerAddress; } /** * @notice Get Latest node that the given zombie at the given index is staked on * @param zombieNum Index of the zombie to lookup * @return Latest node that the given zombie is staked on */ function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint256) { return _zombies[zombieNum].latestStakedNode; } /// @return Current number of un-removed zombies function zombieCount() public view override returns (uint256) { return _zombies.length; } function isZombie(address staker) public view override returns (bool) { for (uint256 i = 0; i < _zombies.length; i++) { if (staker == _zombies[i].stakerAddress) { return true; } } return false; } /** * @notice Get the amount of funds withdrawable by the given address * @param owner Address to check the funds of * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) external view override returns (uint256) { return _withdrawableFunds[owner]; } /** * @return Index of the first unresolved node * @dev If all nodes have been resolved, this will be latestNodeCreated + 1 */ function firstUnresolvedNode() public view override returns (uint256) { return _firstUnresolvedNode; } /// @return Index of the latest confirmed node function latestConfirmed() public view override returns (uint256) { return _latestConfirmed; } /// @return Index of the latest rollup node created function latestNodeCreated() public view override returns (uint256) { return _latestNodeCreated; } /// @return Ethereum block that the most recent stake was created function lastStakeBlock() external view override returns (uint256) { return _lastStakeBlock; } /// @return Number of active stakers currently staked function stakerCount() public view override returns (uint256) { return _stakerList.length; } /** * @notice Initialize the core with an initial node * @param initialNode Initial node to start the chain with */ function initializeCore(INode initialNode) internal { _nodes[0] = initialNode; _firstUnresolvedNode = 1; } /** * @notice React to a new node being created by storing it an incrementing the latest node counter * @param node Node that was newly created * @param nodeHash The hash of said node */ function nodeCreated(INode node, bytes32 nodeHash) internal { _latestNodeCreated++; _nodes[_latestNodeCreated] = node; _nodeHashes[_latestNodeCreated] = nodeHash; } /// @return Node hash as of this node number function getNodeHash(uint256 index) public view override returns (bytes32) { return _nodeHashes[index]; } /// @notice Reject the next unresolved node function _rejectNextNode() internal { destroyNode(_firstUnresolvedNode); _firstUnresolvedNode++; } /// @notice Confirm the next unresolved node function confirmNextNode( bytes32 beforeSendAcc, bytes calldata sendsData, uint256[] calldata sendLengths, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount, IOutbox outbox, RollupEventBridge rollupEventBridge ) internal { confirmNode( _firstUnresolvedNode, beforeSendAcc, sendsData, sendLengths, afterSendCount, afterLogAcc, afterLogCount, outbox, rollupEventBridge ); } function confirmNode( uint256 nodeNum, bytes32 beforeSendAcc, bytes calldata sendsData, uint256[] calldata sendLengths, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount, IOutbox outbox, RollupEventBridge rollupEventBridge ) internal { bytes32 afterSendAcc = RollupLib.feedAccumulator(sendsData, sendLengths, beforeSendAcc); INode node = getNode(nodeNum); // Authenticate data against node's confirm data pre-image require( node.confirmData() == RollupLib.confirmHash( beforeSendAcc, afterSendAcc, afterLogAcc, afterSendCount, afterLogCount ), "CONFIRM_DATA" ); // trusted external call to outbox outbox.processOutgoingMessages(sendsData, sendLengths); destroyNode(_latestConfirmed); _latestConfirmed = nodeNum; _firstUnresolvedNode = nodeNum + 1; rollupEventBridge.nodeConfirmed(nodeNum); emit NodeConfirmed(nodeNum, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount); } /** * @notice Create a new stake at latest confirmed node * @param stakerAddress Address of the new staker * @param depositAmount Stake amount of the new staker */ function createNewStake(address payable stakerAddress, uint256 depositAmount) internal { uint256 stakerIndex = _stakerList.length; _stakerList.push(stakerAddress); _stakerMap[stakerAddress] = Staker( stakerIndex, _latestConfirmed, depositAmount, address(0), // new staker is not in challenge true ); _lastStakeBlock = block.number; emit UserStakeUpdated(stakerAddress, 0, depositAmount); } /** * @notice Check to see whether the two stakers are in the same challenge * @param stakerAddress1 Address of the first staker * @param stakerAddress2 Address of the second staker * @return Address of the challenge that the two stakers are in */ function inChallenge(address stakerAddress1, address stakerAddress2) internal view returns (address) { Staker storage staker1 = _stakerMap[stakerAddress1]; Staker storage staker2 = _stakerMap[stakerAddress2]; address challenge = staker1.currentChallenge; require(challenge != address(0), "NO_CHAL"); require(challenge == staker2.currentChallenge, "DIFF_IN_CHAL"); return challenge; } /** * @notice Make the given staker as not being in a challenge * @param stakerAddress Address of the staker to remove from a challenge */ function clearChallenge(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; staker.currentChallenge = address(0); } /** * @notice Mark both the given stakers as engaged in the challenge * @param staker1 Address of the first staker * @param staker2 Address of the second staker * @param challenge Address of the challenge both stakers are now in */ function challengeStarted( address staker1, address staker2, address challenge ) internal { _stakerMap[staker1].currentChallenge = challenge; _stakerMap[staker2].currentChallenge = challenge; } /** * @notice Add to the stake of the given staker by the given amount * @param stakerAddress Address of the staker to increase the stake of * @param amountAdded Amount of stake to add to the staker */ function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal { Staker storage staker = _stakerMap[stakerAddress]; uint256 initialStaked = staker.amountStaked; uint256 finalStaked = initialStaked.add(amountAdded); staker.amountStaked = finalStaked; emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked); } /** * @notice Reduce the stake of the given staker to the given target * @param stakerAddress Address of the staker to reduce the stake of * @param target Amount of stake to leave with the staker * @return Amount of value released from the stake */ function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) { Staker storage staker = _stakerMap[stakerAddress]; uint256 current = staker.amountStaked; require(target <= current, "TOO_LITTLE_STAKE"); uint256 amountWithdrawn = current.sub(target); staker.amountStaked = target; increaseWithdrawableFunds(stakerAddress, amountWithdrawn); emit UserStakeUpdated(stakerAddress, current, target); return amountWithdrawn; } /** * @notice Remove the given staker and turn them into a zombie * @param stakerAddress Address of the staker to remove */ function turnIntoZombie(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; _zombies.push(Zombie(stakerAddress, staker.latestStakedNode)); deleteStaker(stakerAddress); } /** * @notice Update the latest staked node of the zombie at the given index * @param zombieNum Index of the zombie to move * @param latest New latest node the zombie is staked on */ function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal { _zombies[zombieNum].latestStakedNode = latest; } /** * @notice Remove the zombie at the given index * @param zombieNum Index of the zombie to remove */ function removeZombie(uint256 zombieNum) internal { _zombies[zombieNum] = _zombies[_zombies.length - 1]; _zombies.pop(); } /** * @notice Remove the given staker and return their stake * @param stakerAddress Address of the staker withdrawing their stake */ function withdrawStaker(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; uint256 initialStaked = staker.amountStaked; increaseWithdrawableFunds(stakerAddress, initialStaked); deleteStaker(stakerAddress); emit UserStakeUpdated(stakerAddress, initialStaked, 0); } /** * @notice Advance the given staker to the given node * @param stakerAddress Address of the staker adding their stake * @param nodeNum Index of the node to stake on */ function stakeOnNode( address stakerAddress, uint256 nodeNum, uint256 confirmPeriodBlocks ) internal { Staker storage staker = _stakerMap[stakerAddress]; INode node = _nodes[nodeNum]; uint256 newStakerCount = node.addStaker(stakerAddress); staker.latestStakedNode = nodeNum; if (newStakerCount == 1) { INode parent = _nodes[node.prev()]; parent.newChildConfirmDeadline(block.number.add(confirmPeriodBlocks)); } } /** * @notice Clear the withdrawable funds for the given address * @param owner Address of the account to remove funds from * @return Amount of funds removed from account */ function withdrawFunds(address owner) internal returns (uint256) { uint256 amount = _withdrawableFunds[owner]; _withdrawableFunds[owner] = 0; emit UserWithdrawableFundsUpdated(owner, amount, 0); return amount; } /** * @notice Increase the withdrawable funds for the given address * @param owner Address of the account to add withdrawable funds to */ function increaseWithdrawableFunds(address owner, uint256 amount) internal { uint256 initialWithdrawable = _withdrawableFunds[owner]; uint256 finalWithdrawable = initialWithdrawable.add(amount); _withdrawableFunds[owner] = finalWithdrawable; emit UserWithdrawableFundsUpdated(owner, initialWithdrawable, finalWithdrawable); } /** * @notice Remove the given staker * @param stakerAddress Address of the staker to remove */ function deleteStaker(address stakerAddress) private { Staker storage staker = _stakerMap[stakerAddress]; uint256 stakerIndex = staker.index; _stakerList[stakerIndex] = _stakerList[_stakerList.length - 1]; _stakerMap[_stakerList[stakerIndex]].index = stakerIndex; _stakerList.pop(); delete _stakerMap[stakerAddress]; } /** * @notice Destroy the given node and clear out its address * @param nodeNum Index of the node to remove */ function destroyNode(uint256 nodeNum) internal { _nodes[nodeNum].destroy(); _nodes[nodeNum] = INode(0); } function nodeDeadline( uint256 avmGasSpeedLimitPerBlock, uint256 gasUsed, uint256 confirmPeriodBlocks, INode prevNode ) internal view returns (uint256 deadlineBlock) { // Set deadline rounding up to the nearest block uint256 checkTime = gasUsed.add(avmGasSpeedLimitPerBlock.sub(1)).div(avmGasSpeedLimitPerBlock); deadlineBlock = max(block.number.add(confirmPeriodBlocks), prevNode.deadlineBlock()).add( checkTime ); uint256 olderSibling = prevNode.latestChildNumber(); if (olderSibling != 0) { deadlineBlock = max(deadlineBlock, getNode(olderSibling).deadlineBlock()); } return deadlineBlock; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } struct StakeOnNewNodeFrame { uint256 currentInboxSize; INode node; bytes32 executionHash; INode prevNode; bytes32 lastHash; bool hasSibling; uint256 deadlineBlock; uint256 gasUsed; uint256 sequencerBatchEnd; bytes32 sequencerBatchAcc; } struct CreateNodeDataFrame { uint256 prevNode; uint256 confirmPeriodBlocks; uint256 avmGasSpeedLimitPerBlock; ISequencerInbox sequencerInbox; RollupEventBridge rollupEventBridge; INodeFactory nodeFactory; } uint8 internal constant MAX_SEND_COUNT = 100; function createNewNode( RollupLib.Assertion memory assertion, bytes32[3][2] calldata assertionBytes32Fields, uint256[4][2] calldata assertionIntFields, bytes calldata sequencerBatchProof, CreateNodeDataFrame memory inputDataFrame, bytes32 expectedNodeHash ) internal returns (bytes32 newNodeHash) { StakeOnNewNodeFrame memory memoryFrame; { // validate data memoryFrame.gasUsed = RollupLib.assertionGasUsed(assertion); memoryFrame.prevNode = getNode(inputDataFrame.prevNode); memoryFrame.currentInboxSize = inputDataFrame.sequencerInbox.messageCount(); // Make sure the previous state is correct against the node being built on require( RollupLib.stateHash(assertion.beforeState) == memoryFrame.prevNode.stateHash(), "PREV_STATE_HASH" ); // Ensure that the assertion doesn't read past the end of the current inbox require( assertion.afterState.inboxCount <= memoryFrame.currentInboxSize, "INBOX_PAST_END" ); // Insure inbox tip after assertion is included in a sequencer-inbox batch and return inbox acc; this gives replay protection against the state of the inbox (memoryFrame.sequencerBatchEnd, memoryFrame.sequencerBatchAcc) = inputDataFrame .sequencerInbox .proveInboxContainsMessage(sequencerBatchProof, assertion.afterState.inboxCount); } { memoryFrame.executionHash = RollupLib.executionHash(assertion); memoryFrame.deadlineBlock = nodeDeadline( inputDataFrame.avmGasSpeedLimitPerBlock, memoryFrame.gasUsed, inputDataFrame.confirmPeriodBlocks, memoryFrame.prevNode ); memoryFrame.hasSibling = memoryFrame.prevNode.latestChildNumber() > 0; // here we don't use ternacy operator to remain compatible with slither if (memoryFrame.hasSibling) { memoryFrame.lastHash = getNodeHash(memoryFrame.prevNode.latestChildNumber()); } else { memoryFrame.lastHash = getNodeHash(inputDataFrame.prevNode); } memoryFrame.node = INode( inputDataFrame.nodeFactory.createNode( RollupLib.stateHash(assertion.afterState), RollupLib.challengeRoot(assertion, memoryFrame.executionHash, block.number), RollupLib.confirmHash(assertion), inputDataFrame.prevNode, memoryFrame.deadlineBlock ) ); } { uint256 nodeNum = latestNodeCreated() + 1; memoryFrame.prevNode.childCreated(nodeNum); newNodeHash = RollupLib.nodeHash( memoryFrame.hasSibling, memoryFrame.lastHash, memoryFrame.executionHash, memoryFrame.sequencerBatchAcc ); require(newNodeHash == expectedNodeHash, "UNEXPECTED_NODE_HASH"); nodeCreated(memoryFrame.node, newNodeHash); inputDataFrame.rollupEventBridge.nodeCreated( nodeNum, inputDataFrame.prevNode, memoryFrame.deadlineBlock, msg.sender ); } emit NodeCreated( latestNodeCreated(), getNodeHash(inputDataFrame.prevNode), newNodeHash, memoryFrame.executionHash, memoryFrame.currentInboxSize, memoryFrame.sequencerBatchEnd, memoryFrame.sequencerBatchAcc, assertionBytes32Fields, assertionIntFields ); return newNodeHash; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../challenge/ChallengeLib.sol"; import "./INode.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library RollupLib { using SafeMath for uint256; struct Config { bytes32 machineHash; uint256 confirmPeriodBlocks; uint256 extraChallengeTimeBlocks; uint256 avmGasSpeedLimitPerBlock; uint256 baseStake; address stakeToken; address owner; address sequencer; uint256 sequencerDelayBlocks; uint256 sequencerDelaySeconds; bytes extraConfig; } struct ExecutionState { uint256 gasUsed; bytes32 machineHash; uint256 inboxCount; uint256 sendCount; uint256 logCount; bytes32 sendAcc; bytes32 logAcc; uint256 proposedBlock; uint256 inboxMaxCount; } function stateHash(ExecutionState memory execState) internal pure returns (bytes32) { return keccak256( abi.encodePacked( execState.gasUsed, execState.machineHash, execState.inboxCount, execState.sendCount, execState.logCount, execState.sendAcc, execState.logAcc, execState.proposedBlock, execState.inboxMaxCount ) ); } struct Assertion { ExecutionState beforeState; ExecutionState afterState; } function decodeExecutionState( bytes32[3] memory bytes32Fields, uint256[4] memory intFields, uint256 proposedBlock, uint256 inboxMaxCount ) internal pure returns (ExecutionState memory) { return ExecutionState( intFields[0], bytes32Fields[0], intFields[1], intFields[2], intFields[3], bytes32Fields[1], bytes32Fields[2], proposedBlock, inboxMaxCount ); } function decodeAssertion( bytes32[3][2] memory bytes32Fields, uint256[4][2] memory intFields, uint256 beforeProposedBlock, uint256 beforeInboxMaxCount, uint256 inboxMaxCount ) internal view returns (Assertion memory) { return Assertion( decodeExecutionState( bytes32Fields[0], intFields[0], beforeProposedBlock, beforeInboxMaxCount ), decodeExecutionState(bytes32Fields[1], intFields[1], block.number, inboxMaxCount) ); } function executionStateChallengeHash(ExecutionState memory state) internal pure returns (bytes32) { return ChallengeLib.assertionHash( state.gasUsed, ChallengeLib.assertionRestHash( state.inboxCount, state.machineHash, state.sendAcc, state.sendCount, state.logAcc, state.logCount ) ); } function executionHash(Assertion memory assertion) internal pure returns (bytes32) { return ChallengeLib.bisectionChunkHash( assertion.beforeState.gasUsed, assertion.afterState.gasUsed - assertion.beforeState.gasUsed, RollupLib.executionStateChallengeHash(assertion.beforeState), RollupLib.executionStateChallengeHash(assertion.afterState) ); } function assertionGasUsed(RollupLib.Assertion memory assertion) internal pure returns (uint256) { return assertion.afterState.gasUsed.sub(assertion.beforeState.gasUsed); } function challengeRoot( Assertion memory assertion, bytes32 assertionExecHash, uint256 blockProposed ) internal pure returns (bytes32) { return challengeRootHash(assertionExecHash, blockProposed, assertion.afterState.inboxCount); } function challengeRootHash( bytes32 execution, uint256 proposedTime, uint256 maxMessageCount ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(execution, proposedTime, maxMessageCount)); } function confirmHash(Assertion memory assertion) internal pure returns (bytes32) { return confirmHash( assertion.beforeState.sendAcc, assertion.afterState.sendAcc, assertion.afterState.logAcc, assertion.afterState.sendCount, assertion.afterState.logCount ); } function confirmHash( bytes32 beforeSendAcc, bytes32 afterSendAcc, bytes32 afterLogAcc, uint256 afterSendCount, uint256 afterLogCount ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( beforeSendAcc, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount ) ); } function feedAccumulator( bytes memory messageData, uint256[] memory messageLengths, bytes32 beforeAcc ) internal pure returns (bytes32) { uint256 offset = 0; uint256 messageCount = messageLengths.length; uint256 dataLength = messageData.length; bytes32 messageAcc = beforeAcc; for (uint256 i = 0; i < messageCount; i++) { uint256 messageLength = messageLengths[i]; require(offset + messageLength <= dataLength, "DATA_OVERRUN"); bytes32 messageHash; assembly { messageHash := keccak256(add(messageData, add(offset, 32)), messageLength) } messageAcc = keccak256(abi.encodePacked(messageAcc, messageHash)); offset += messageLength; } require(offset == dataLength, "DATA_LENGTH"); return messageAcc; } function nodeHash( bool hasSibling, bytes32 lastHash, bytes32 assertionExecHash, bytes32 inboxAcc ) internal pure returns (bytes32) { uint8 hasSiblingInt = hasSibling ? 1 : 0; return keccak256(abi.encodePacked(hasSiblingInt, lastHash, assertionExecHash, inboxAcc)); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface INodeFactory { function createNode( bytes32 _stateHash, bytes32 _challengeHash, bytes32 _confirmData, uint256 _prev, uint256 _deadlineBlock ) external returns (address); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; import "../arch/IOneStepProof.sol"; interface IChallenge { function initializeChallenge( IOneStepProof[] calldata _executors, address _resultReceiver, bytes32 _executionHash, uint256 _maxMessageCount, address _asserter, address _challenger, uint256 _asserterTimeLeft, uint256 _challengerTimeLeft, ISequencerInbox _sequencerBridge, IBridge _delayedBridge ) external; function currentResponderTimeLeft() external view returns (uint256); function lastMoveBlock() external view returns (uint256); function timeout() external; function asserter() external view returns (address); function challenger() external view returns (address); function clearChallenge() external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; interface IChallengeFactory { function createChallenge( address _resultReceiver, bytes32 _executionHash, uint256 _maxMessageCount, address _asserter, address _challenger, uint256 _asserterTimeLeft, uint256 _challengerTimeLeft, ISequencerInbox _sequencerBridge, IBridge _delayedBridge ) external returns (address); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface IOutbox { event OutboxEntryCreated( uint256 indexed batchNum, uint256 outboxEntryIndex, bytes32 outputRoot, uint256 numInBatch ); event OutBoxTransactionExecuted( address indexed destAddr, address indexed l2Sender, uint256 indexed outboxEntryIndex, uint256 transactionIndex ); function l2ToL1Sender() external view returns (address); function l2ToL1Block() external view returns (uint256); function l2ToL1EthBlock() external view returns (uint256); function l2ToL1Timestamp() external view returns (uint256); function l2ToL1BatchNum() external view returns (uint256); function l2ToL1OutputId() external view returns (bytes32); function processOutgoingMessages(bytes calldata sendsData, uint256[] calldata sendLengths) external; function outboxEntryExists(uint256 batchNum) external view returns (bool); function executeTransaction( uint256 outboxIndex, bytes32[] calldata proof, uint256 index, address l2Sender, address destAddr, uint256 l2Block, uint256 l1Block, uint256 l2Timestamp, uint256 amount, bytes calldata calldataForL1) external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; library Messages { function messageHash( uint8 kind, address sender, uint256 blockNumber, uint256 timestamp, uint256 inboxSeqNum, uint256 gasPriceL1, bytes32 messageDataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( kind, sender, blockNumber, timestamp, inboxSeqNum, gasPriceL1, messageDataHash ) ); } function addMessageToInbox(bytes32 inbox, bytes32 message) internal pure returns (bytes32) { return keccak256(abi.encodePacked(inbox, message)); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; library ProxyUtil { function getProxyAdmin() internal view returns (address admin) { // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/TransparentUpgradeableProxy.sol#L48 // Storage slot with the admin of the proxy contract. // This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is bytes32 slot = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; assembly { admin := sload(slot) } } } // 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: Apache-2.0 /* * Copyright 2019, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface ICloneable { function isMaster() external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./INode.sol"; interface IRollupCore { function _stakerMap(address stakerAddress) external view returns ( uint256, uint256, uint256, address, bool ); event RollupCreated(bytes32 machineHash); event NodeCreated( uint256 indexed nodeNum, bytes32 indexed parentNodeHash, bytes32 nodeHash, bytes32 executionHash, uint256 inboxMaxCount, uint256 afterInboxBatchEndCount, bytes32 afterInboxBatchAcc, bytes32[3][2] assertionBytes32Fields, uint256[4][2] assertionIntFields ); event NodeConfirmed( uint256 indexed nodeNum, bytes32 afterSendAcc, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount ); event NodeRejected(uint256 indexed nodeNum); event RollupChallengeStarted( address indexed challengeContract, address asserter, address challenger, uint256 challengedNode ); event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance); event UserWithdrawableFundsUpdated( address indexed user, uint256 initialBalance, uint256 finalBalance ); function getNode(uint256 nodeNum) external view returns (INode); /** * @notice Get the address of the staker at the given index * @param stakerNum Index of the staker * @return Address of the staker */ function getStakerAddress(uint256 stakerNum) external view returns (address); /** * @notice Check whether the given staker is staked * @param staker Staker address to check * @return True or False for whether the staker was staked */ function isStaked(address staker) external view returns (bool); /** * @notice Get the latest staked node of the given staker * @param staker Staker address to lookup * @return Latest node staked of the staker */ function latestStakedNode(address staker) external view returns (uint256); /** * @notice Get the current challenge of the given staker * @param staker Staker address to lookup * @return Current challenge of the staker */ function currentChallenge(address staker) external view returns (address); /** * @notice Get the amount staked of the given staker * @param staker Staker address to lookup * @return Amount staked of the staker */ function amountStaked(address staker) external view returns (uint256); /** * @notice Get the original staker address of the zombie at the given index * @param zombieNum Index of the zombie to lookup * @return Original staker address of the zombie */ function zombieAddress(uint256 zombieNum) external view returns (address); /** * @notice Get Latest node that the given zombie at the given index is staked on * @param zombieNum Index of the zombie to lookup * @return Latest node that the given zombie is staked on */ function zombieLatestStakedNode(uint256 zombieNum) external view returns (uint256); /// @return Current number of un-removed zombies function zombieCount() external view returns (uint256); function isZombie(address staker) external view returns (bool); /** * @notice Get the amount of funds withdrawable by the given address * @param owner Address to check the funds of * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) external view returns (uint256); /** * @return Index of the first unresolved node * @dev If all nodes have been resolved, this will be latestNodeCreated + 1 */ function firstUnresolvedNode() external view returns (uint256); /// @return Index of the latest confirmed node function latestConfirmed() external view returns (uint256); /// @return Index of the latest rollup node created function latestNodeCreated() external view returns (uint256); /// @return Ethereum block that the most recent stake was created function lastStakeBlock() external view returns (uint256); /// @return Number of active stakers currently staked function stakerCount() external view returns (uint256); /// @return Node hash as of this node number function getNodeHash(uint256 index) external view returns (bytes32); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; interface ISequencerInbox { event SequencerBatchDelivered( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, bytes32 afterAcc, bytes transactions, uint256[] lengths, uint256[] sectionsMetadata, uint256 seqBatchIndex, address sequencer ); event SequencerBatchDeliveredFromOrigin( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, bytes32 afterAcc, uint256 seqBatchIndex ); event DelayedInboxForced( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, uint256 totalDelayedMessagesRead, bytes32[2] afterAccAndDelayed, uint256 seqBatchIndex ); /// @notice DEPRECATED - look at IsSequencerUpdated for new updates // event SequencerAddressUpdated(address newAddress); event IsSequencerUpdated(address addr, bool isSequencer); event MaxDelayUpdated(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds); /// @notice DEPRECATED - look at MaxDelayUpdated for new updates // event MaxDelayBlocksUpdated(uint256 newValue); /// @notice DEPRECATED - look at MaxDelayUpdated for new updates // event MaxDelaySecondsUpdated(uint256 newValue); function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external; function setIsSequencer(address addr, bool isSequencer) external; function messageCount() external view returns (uint256); function maxDelayBlocks() external view returns (uint256); function maxDelaySeconds() external view returns (uint256); function inboxAccs(uint256 index) external view returns (bytes32); function getInboxAccsLength() external view returns (uint256); function proveInboxContainsMessage(bytes calldata proof, uint256 inboxCount) external view returns (uint256, bytes32); /// @notice DEPRECATED - use isSequencer instead function sequencer() external view returns (address); function isSequencer(address seq) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../libraries/MerkleLib.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library ChallengeLib { using SafeMath for uint256; function firstSegmentSize(uint256 totalCount, uint256 bisectionCount) internal pure returns (uint256) { return totalCount / bisectionCount + (totalCount % bisectionCount); } function otherSegmentSize(uint256 totalCount, uint256 bisectionCount) internal pure returns (uint256) { return totalCount / bisectionCount; } function bisectionChunkHash( uint256 _segmentStart, uint256 _segmentLength, bytes32 _startHash, bytes32 _endHash ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_segmentStart, _segmentLength, _startHash, _endHash)); } function assertionHash(uint256 _avmGasUsed, bytes32 _restHash) internal pure returns (bytes32) { // Note: make sure this doesn't return Challenge.UNREACHABLE_ASSERTION (currently 0) return keccak256(abi.encodePacked(_avmGasUsed, _restHash)); } function assertionRestHash( uint256 _totalMessagesRead, bytes32 _machineState, bytes32 _sendAcc, uint256 _sendCount, bytes32 _logAcc, uint256 _logCount ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _totalMessagesRead, _machineState, _sendAcc, _sendCount, _logAcc, _logCount ) ); } function updatedBisectionRoot( bytes32[] memory _chainHashes, uint256 _challengedSegmentStart, uint256 _challengedSegmentLength ) internal pure returns (bytes32) { uint256 bisectionCount = _chainHashes.length - 1; bytes32[] memory hashes = new bytes32[](bisectionCount); uint256 chunkSize = ChallengeLib.firstSegmentSize(_challengedSegmentLength, bisectionCount); uint256 segmentStart = _challengedSegmentStart; hashes[0] = ChallengeLib.bisectionChunkHash( segmentStart, chunkSize, _chainHashes[0], _chainHashes[1] ); segmentStart = segmentStart.add(chunkSize); chunkSize = ChallengeLib.otherSegmentSize(_challengedSegmentLength, bisectionCount); for (uint256 i = 1; i < bisectionCount; i++) { hashes[i] = ChallengeLib.bisectionChunkHash( segmentStart, chunkSize, _chainHashes[i], _chainHashes[i + 1] ); segmentStart = segmentStart.add(chunkSize); } return MerkleLib.generateRoot(hashes); } function verifySegmentProof( bytes32 challengeState, bytes32 item, bytes32[] calldata _merkleNodes, uint256 _merkleRoute ) internal pure returns (bool) { return challengeState == MerkleLib.calculateRoot(_merkleNodes, _merkleRoute, item); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; library MerkleLib { function generateRoot(bytes32[] memory _hashes) internal pure returns (bytes32) { bytes32[] memory prevLayer = _hashes; while (prevLayer.length > 1) { bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2); for (uint256 i = 0; i < nextLayer.length; i++) { if (2 * i + 1 < prevLayer.length) { nextLayer[i] = keccak256( abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1]) ); } else { nextLayer[i] = prevLayer[2 * i]; } } prevLayer = nextLayer; } return prevLayer[0]; } function calculateRoot( bytes32[] memory nodes, uint256 route, bytes32 item ) internal pure returns (bytes32) { uint256 proofItems = nodes.length; require(proofItems <= 256); bytes32 h = item; for (uint256 i = 0; i < proofItems; i++) { if (route % 2 == 0) { h = keccak256(abi.encodePacked(nodes[i], h)); } else { h = keccak256(abi.encodePacked(h, nodes[i])); } route /= 2; } return h; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; interface IOneStepProof { // Bridges is sequencer bridge then delayed bridge function executeStep( address[2] calldata bridges, uint256 initialMessagesRead, bytes32[2] calldata accs, bytes calldata proof, bytes calldata bproof ) external view returns ( uint64 gas, uint256 afterMessagesRead, bytes32[4] memory fields ); function executeStepDebug( address[2] calldata bridges, uint256 initialMessagesRead, bytes32[2] calldata accs, bytes calldata proof, bytes calldata bproof ) external view returns (string memory startMachine, string memory afterMachine); }
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function and {_fallback} should delegate./ if there is an owner and it is the sender, delegate to admin facet
function _implementation() internal view virtual override returns (address) { require(msg.data.length >= 4, "NO_FUNC_SIG"); address rollupOwner = owner; address target = rollupOwner != address(0) && rollupOwner == msg.sender ? getAdminFacet() : getUserFacet(); require(target.isContract(), "TARGET_NOT_CONTRACT"); return target; }
577,781
[ 1, 2503, 353, 279, 5024, 445, 716, 1410, 506, 31736, 1427, 518, 1135, 326, 1758, 358, 1492, 326, 5922, 445, 471, 288, 67, 16471, 97, 1410, 7152, 18, 19, 309, 1915, 353, 392, 3410, 471, 518, 353, 326, 5793, 16, 7152, 358, 3981, 11082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 30810, 1435, 2713, 1476, 5024, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 2583, 12, 3576, 18, 892, 18, 2469, 1545, 1059, 16, 315, 3417, 67, 42, 21163, 67, 18513, 8863, 203, 3639, 1758, 5824, 416, 5541, 273, 3410, 31, 203, 3639, 1758, 1018, 273, 5824, 416, 5541, 480, 1758, 12, 20, 13, 597, 5824, 416, 5541, 422, 1234, 18, 15330, 203, 5411, 692, 22501, 11137, 1435, 203, 5411, 294, 4735, 11137, 5621, 203, 3639, 2583, 12, 3299, 18, 291, 8924, 9334, 315, 16374, 67, 4400, 67, 6067, 2849, 1268, 8863, 203, 3639, 327, 1018, 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 ]
pragma solidity ^0.4.13; /** * @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 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 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); } contract AbstractStarbaseToken is ERC20 { function isFundraiser(address fundraiserAddress) public returns (bool); function company() public returns (address); function allocateToCrowdsalePurchaser(address to, uint256 value) public returns (bool); function allocateToMarketingSupporter(address to, uint256 value) public returns (bool); } contract AbstractStarbaseCrowdsale { function workshop() constant returns (address) {} function startDate() constant returns (uint256) {} function endedAt() constant returns (uint256) {} function isEnded() constant returns (bool); function totalRaisedAmountInCny() constant returns (uint256); function numOfPurchasedTokensOnCsBy(address purchaser) constant returns (uint256); function numOfPurchasedTokensOnEpBy(address purchaser) constant returns (uint256); } // @title EarlyPurchase contract - Keep track of purchased amount by Early Purchasers /// @author Starbase PTE. LTD. - <[email protected]> contract StarbaseEarlyPurchase { /* * Constants */ string public constant PURCHASE_AMOUNT_UNIT = 'CNY'; // Chinese Yuan string public constant PURCHASE_AMOUNT_RATE_REFERENCE = 'http://www.xe.com/currencytables/'; uint256 public constant PURCHASE_AMOUNT_CAP = 9000000; /* * Types */ struct EarlyPurchase { address purchaser; uint256 amount; // CNY based amount uint256 purchasedAt; // timestamp } /* * External contracts */ AbstractStarbaseCrowdsale public starbaseCrowdsale; /* * Storage */ address public owner; EarlyPurchase[] public earlyPurchases; uint256 public earlyPurchaseClosedAt; /* * Modifiers */ modifier noEther() { require(msg.value == 0); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyBeforeCrowdsale() { assert(address(starbaseCrowdsale) == address(0) || starbaseCrowdsale.startDate() == 0); _; } modifier onlyEarlyPurchaseTerm() { assert(earlyPurchaseClosedAt <= 0); _; } /* * Contract functions */ /** * @dev Returns early purchased amount by purchaser's address * @param purchaser Purchaser address */ function purchasedAmountBy(address purchaser) external constant noEther returns (uint256 amount) { for (uint256 i; i < earlyPurchases.length; i++) { if (earlyPurchases[i].purchaser == purchaser) { amount += earlyPurchases[i].amount; } } } /** * @dev Returns total amount of raised funds by Early Purchasers */ function totalAmountOfEarlyPurchases() constant noEther public returns (uint256 totalAmount) { for (uint256 i; i < earlyPurchases.length; i++) { totalAmount += earlyPurchases[i].amount; } } /** * @dev Returns number of early purchases */ function numberOfEarlyPurchases() external constant noEther returns (uint256) { return earlyPurchases.length; } /** * @dev Append an early purchase log * @param purchaser Purchaser address * @param amount Purchase amount * @param purchasedAt Timestamp of purchased date */ function appendEarlyPurchase(address purchaser, uint256 amount, uint256 purchasedAt) external noEther onlyOwner onlyBeforeCrowdsale onlyEarlyPurchaseTerm returns (bool) { if (amount == 0 || totalAmountOfEarlyPurchases() + amount > PURCHASE_AMOUNT_CAP) { return false; } assert(purchasedAt != 0 || purchasedAt <= now); earlyPurchases.push(EarlyPurchase(purchaser, amount, purchasedAt)); return true; } /** * @dev Close early purchase term */ function closeEarlyPurchase() external noEther onlyOwner returns (bool) { earlyPurchaseClosedAt = now; } /** * @dev Setup function sets external contract's address * @param starbaseCrowdsaleAddress Token address */ function setup(address starbaseCrowdsaleAddress) external noEther onlyOwner returns (bool) { if (address(starbaseCrowdsale) == 0) { starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddress); return true; } return false; } /** * @dev Contract constructor function */ function StarbaseEarlyPurchase() noEther { owner = msg.sender; } } /// @title EarlyPurchaseAmendment contract - Amend early purchase records of the original contract /// @author Starbase PTE. LTD. - <[email protected]> contract StarbaseEarlyPurchaseAmendment { /* * Events */ event EarlyPurchaseInvalidated(uint256 epIdx); event EarlyPurchaseAmended(uint256 epIdx); /* * External contracts */ AbstractStarbaseCrowdsale public starbaseCrowdsale; StarbaseEarlyPurchase public starbaseEarlyPurchase; /* * Storage */ address public owner; uint256[] public invalidEarlyPurchaseIndexes; uint256[] public amendedEarlyPurchaseIndexes; mapping (uint256 => StarbaseEarlyPurchase.EarlyPurchase) public amendedEarlyPurchases; /* * Modifiers */ modifier noEther() { require(msg.value == 0); _; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyBeforeCrowdsale() { assert(address(starbaseCrowdsale) == address(0) || starbaseCrowdsale.startDate() == 0); _; } modifier onlyEarlyPurchasesLoaded() { assert(address(starbaseEarlyPurchase) != address(0)); _; } /* * Functions below are compatible with starbaseEarlyPurchase contract */ /** * @dev Returns an early purchase record * @param earlyPurchaseIndex Index number of an early purchase */ function earlyPurchases(uint256 earlyPurchaseIndex) external constant onlyEarlyPurchasesLoaded returns (address purchaser, uint256 amount, uint256 purchasedAt) { return starbaseEarlyPurchase.earlyPurchases(earlyPurchaseIndex); } /** * @dev Returns early purchased amount by purchaser's address * @param purchaser Purchaser address */ function purchasedAmountBy(address purchaser) external constant noEther returns (uint256 amount) { StarbaseEarlyPurchase.EarlyPurchase[] memory normalizedEP = normalizedEarlyPurchases(); for (uint256 i; i < normalizedEP.length; i++) { if (normalizedEP[i].purchaser == purchaser) { amount += normalizedEP[i].amount; } } } /** * @dev Returns total amount of raised funds by Early Purchasers */ function totalAmountOfEarlyPurchases() constant noEther public returns (uint256 totalAmount) { StarbaseEarlyPurchase.EarlyPurchase[] memory normalizedEP = normalizedEarlyPurchases(); for (uint256 i; i < normalizedEP.length; i++) { totalAmount += normalizedEP[i].amount; } } /** * @dev Returns number of early purchases */ function numberOfEarlyPurchases() external constant noEther returns (uint256) { return normalizedEarlyPurchases().length; } /** * @dev Sets up function sets external contract's address * @param starbaseCrowdsaleAddress Token address */ function setup(address starbaseCrowdsaleAddress) external noEther onlyOwner returns (bool) { if (address(starbaseCrowdsale) == 0) { starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddress); return true; } return false; } /* * Contract functions unique to StarbaseEarlyPurchaseAmendment */ /** * @dev Invalidate early purchase * @param earlyPurchaseIndex Index number of the purchase */ function invalidateEarlyPurchase(uint256 earlyPurchaseIndex) external noEther onlyOwner onlyEarlyPurchasesLoaded onlyBeforeCrowdsale returns (bool) { assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex); // Array Index Out of Bounds Exception for (uint256 i; i < invalidEarlyPurchaseIndexes.length; i++) { assert(invalidEarlyPurchaseIndexes[i] != earlyPurchaseIndex); } invalidEarlyPurchaseIndexes.push(earlyPurchaseIndex); EarlyPurchaseInvalidated(earlyPurchaseIndex); return true; } /** * @dev Checks whether early purchase is invalid * @param earlyPurchaseIndex Index number of the purchase */ function isInvalidEarlyPurchase(uint256 earlyPurchaseIndex) constant noEther public returns (bool) { assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex); // Array Index Out of Bounds Exception for (uint256 i; i < invalidEarlyPurchaseIndexes.length; i++) { if (invalidEarlyPurchaseIndexes[i] == earlyPurchaseIndex) { return true; } } return false; } /** * @dev Amends a given early purchase with data * @param earlyPurchaseIndex Index number of the purchase * @param purchaser Purchaser's address * @param amount Value of purchase * @param purchasedAt Purchase timestamp */ function amendEarlyPurchase(uint256 earlyPurchaseIndex, address purchaser, uint256 amount, uint256 purchasedAt) external noEther onlyOwner onlyEarlyPurchasesLoaded onlyBeforeCrowdsale returns (bool) { assert(purchasedAt != 0 || purchasedAt <= now); assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex); assert(!isInvalidEarlyPurchase(earlyPurchaseIndex)); // Invalid early purchase cannot be amended if (!isAmendedEarlyPurchase(earlyPurchaseIndex)) { amendedEarlyPurchaseIndexes.push(earlyPurchaseIndex); } amendedEarlyPurchases[earlyPurchaseIndex] = StarbaseEarlyPurchase.EarlyPurchase(purchaser, amount, purchasedAt); EarlyPurchaseAmended(earlyPurchaseIndex); return true; } /** * @dev Checks whether early purchase is amended * @param earlyPurchaseIndex Index number of the purchase */ function isAmendedEarlyPurchase(uint256 earlyPurchaseIndex) constant noEther returns (bool) { assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex); // Array Index Out of Bounds Exception for (uint256 i; i < amendedEarlyPurchaseIndexes.length; i++) { if (amendedEarlyPurchaseIndexes[i] == earlyPurchaseIndex) { return true; } } return false; } /** * @dev Loads early purchases data to StarbaseEarlyPurchaseAmendment contract * @param starbaseEarlyPurchaseAddress Address from starbase early purchase */ function loadStarbaseEarlyPurchases(address starbaseEarlyPurchaseAddress) external noEther onlyOwner onlyBeforeCrowdsale returns (bool) { assert(starbaseEarlyPurchaseAddress != 0 || address(starbaseEarlyPurchase) == 0); starbaseEarlyPurchase = StarbaseEarlyPurchase(starbaseEarlyPurchaseAddress); assert(starbaseEarlyPurchase.earlyPurchaseClosedAt() != 0); // the early purchase must be closed return true; } /** * @dev Contract constructor function. It sets owner */ function StarbaseEarlyPurchaseAmendment() noEther { owner = msg.sender; } /** * Internal functions */ /** * @dev Normalizes early purchases data */ function normalizedEarlyPurchases() constant internal returns (StarbaseEarlyPurchase.EarlyPurchase[] normalizedEP) { uint256 rawEPCount = numberOfRawEarlyPurchases(); normalizedEP = new StarbaseEarlyPurchase.EarlyPurchase[]( rawEPCount - invalidEarlyPurchaseIndexes.length); uint256 normalizedIdx; for (uint256 i; i < rawEPCount; i++) { if (isInvalidEarlyPurchase(i)) { continue; // invalid early purchase should be ignored } StarbaseEarlyPurchase.EarlyPurchase memory ep; if (isAmendedEarlyPurchase(i)) { ep = amendedEarlyPurchases[i]; // amended early purchase should take a priority } else { ep = getEarlyPurchase(i); } normalizedEP[normalizedIdx] = ep; normalizedIdx++; } } /** * @dev Fetches early purchases data */ function getEarlyPurchase(uint256 earlyPurchaseIndex) internal constant onlyEarlyPurchasesLoaded returns (StarbaseEarlyPurchase.EarlyPurchase) { var (purchaser, amount, purchasedAt) = starbaseEarlyPurchase.earlyPurchases(earlyPurchaseIndex); return StarbaseEarlyPurchase.EarlyPurchase(purchaser, amount, purchasedAt); } /** * @dev Returns raw number of early purchases */ function numberOfRawEarlyPurchases() internal constant onlyEarlyPurchasesLoaded returns (uint256) { return starbaseEarlyPurchase.numberOfEarlyPurchases(); } } /** * @title Crowdsale contract - Starbase crowdsale to create STAR. * @author Starbase PTE. LTD. - <[email protected]> */ contract StarbaseCrowdsale is Ownable { /* * Events */ event CrowdsaleEnded(uint256 endedAt); event StarBasePurchasedWithEth(address purchaser, uint256 amount, uint256 rawAmount, uint256 cnyEthRate, uint256 bonusTokensPercentage); event StarBasePurchasedOffChain(address purchaser, uint256 amount, uint256 rawAmount, uint256 cnyBtcRate, uint256 bonusTokensPercentage, string data); event CnyEthRateUpdated(uint256 cnyEthRate); event CnyBtcRateUpdated(uint256 cnyBtcRate); event QualifiedPartnerAddress(address qualifiedPartner); event PurchaseInvalidated(uint256 purchaseIdx); event PurchaseAmended(uint256 purchaseIdx); /** * External contracts */ AbstractStarbaseToken public starbaseToken; StarbaseEarlyPurchaseAmendment public starbaseEpAmendment; /** * Constants */ uint256 constant public crowdsaleTokenAmount = 125000000e18; uint256 constant public earlyPurchaseTokenAmount = 50000000e18; uint256 constant public MIN_INVESTMENT = 1; // min is 1 Wei uint256 constant public MAX_CROWDSALE_CAP = 60000000; // approximately 9M USD for the crowdsale(CS). 1M (by EP) + 9M (by CS) = 10M (Total) string public constant PURCHASE_AMOUNT_UNIT = 'CNY'; // Chinese Yuan /** * Types */ struct CrowdsalePurchase { address purchaser; uint256 amount; // CNY based amount with bonus uint256 rawAmount; // CNY based amount no bonus uint256 purchasedAt; // timestamp string data; // additional data (e.g. Tx ID of Bitcoin) uint256 bonus; } struct QualifiedPartners { uint256 amountCap; uint256 amountRaised; bool bonaFide; uint256 commissionFeePercentage; // example 5 will calculate the percentage as 5% } /** * Storage */ address public workshop; // holds undelivered STARs uint public numOfDeliveredCrowdsalePurchases = 0; // index to keep the number of crowdsale purchases have already been processed by `deliverPurchasedTokens` uint public numOfDeliveredEarlyPurchases = 0; // index to keep the number of early purchases have already been processed by `deliverPurchasedTokens` uint256 public numOfLoadedEarlyPurchases = 0; // index to keep the number of early purchases that have already been loaded by `loadEarlyPurchases` address[] public earlyPurchasers; mapping (address => QualifiedPartners) public qualifiedPartners; mapping (address => uint256) public earlyPurchasedAmountBy; // early purchased amount in CNY per purchasers' address bool public earlyPurchasesLoaded = false; // returns whether all early purchases are loaded into this contract // crowdsale uint256 public purchaseStartBlock; // crowdsale purchases can be accepted from this block number uint256 public startDate; uint256 public endedAt; CrowdsalePurchase[] public crowdsalePurchases; uint256 public cnyBtcRate; // this rate won't be used from a smart contract function but external system uint256 public cnyEthRate; // bonus milestones uint256 public firstBonusSalesEnds; uint256 public secondBonusSalesEnds; uint256 public thirdBonusSalesEnds; uint256 public fourthBonusSalesEnds; uint256 public fifthBonusSalesEnds; uint256 public firstExtendedBonusSalesEnds; uint256 public secondExtendedBonusSalesEnds; uint256 public thirdExtendedBonusSalesEnds; uint256 public fourthExtendedBonusSalesEnds; uint256 public fifthExtendedBonusSalesEnds; uint256 public sixthExtendedBonusSalesEnds; // after the crowdsale mapping(uint256 => CrowdsalePurchase) public invalidatedOrigPurchases; // Original purchase which was invalidated by owner mapping(uint256 => CrowdsalePurchase) public amendedOrigPurchases; // Original purchase which was amended by owner mapping (address => uint256) public numOfPurchasedTokensOnCsBy; // the number of tokens purchased on the crowdsale by a purchaser mapping (address => uint256) public numOfPurchasedTokensOnEpBy; // the number of tokens early purchased by a purchaser /** * Modifiers */ modifier minInvestment() { // User has to send at least the ether value of one token. assert(msg.value >= MIN_INVESTMENT); _; } modifier whenEnded() { assert(isEnded()); _; } modifier hasBalance() { assert(this.balance > 0); _; } modifier rateIsSet(uint256 _rate) { assert(_rate != 0); _; } modifier whenNotEnded() { assert(!isEnded()); _; } modifier tokensNotDelivered() { assert(numOfDeliveredCrowdsalePurchases == 0); assert(numOfDeliveredEarlyPurchases == 0); _; } modifier onlyFundraiser() { assert(address(starbaseToken) != 0); assert(starbaseToken.isFundraiser(msg.sender)); _; } /** * Contract functions */ /** * @dev Contract constructor function sets owner and start date. * @param workshopAddr The address that will hold undelivered Star tokens * @param starbaseEpAddr The address that holds the early purchasers Star tokens */ function StarbaseCrowdsale(address workshopAddr, address starbaseEpAddr) { require(workshopAddr != 0 && starbaseEpAddr != 0); owner = msg.sender; workshop = workshopAddr; starbaseEpAmendment = StarbaseEarlyPurchaseAmendment(starbaseEpAddr); } /** * @dev Fallback accepts payment for Star tokens with Eth */ function() payable { redirectToPurchase(); } /** * External functions */ /** * @dev Setup function sets external contracts' addresses. * @param starbaseTokenAddress Token address. * @param _purchaseStartBlock Block number to start crowdsale */ function setup(address starbaseTokenAddress, uint256 _purchaseStartBlock) external onlyOwner returns (bool) { assert(address(starbaseToken) == 0); starbaseToken = AbstractStarbaseToken(starbaseTokenAddress); purchaseStartBlock = _purchaseStartBlock; return true; } /** * @dev Allows owner to record a purchase made outside of Ethereum blockchain * @param purchaser Address of a purchaser * @param rawAmount Purchased amount in CNY * @param purchasedAt Timestamp at the purchase made * @param data Identifier as an evidence of the purchase (e.g. btc:1xyzxyz) */ function recordOffchainPurchase( address purchaser, uint256 rawAmount, uint256 purchasedAt, string data ) external onlyFundraiser whenNotEnded rateIsSet(cnyBtcRate) returns (bool) { require(purchaseStartBlock > 0 && block.number >= purchaseStartBlock); if (startDate == 0) { startCrowdsale(block.timestamp); } uint256 bonusTier = getBonusTier(); uint amount = recordPurchase(purchaser, rawAmount, purchasedAt, data, bonusTier); StarBasePurchasedOffChain(purchaser, amount, rawAmount, cnyBtcRate, bonusTier, data); return true; } /** * @dev Transfers raised funds to company's wallet address at any given time. */ function withdrawForCompany() external onlyFundraiser hasBalance { address company = starbaseToken.company(); require(company != address(0)); company.transfer(this.balance); } /** * @dev Update the CNY/ETH rate to record purchases in CNY */ function updateCnyEthRate(uint256 rate) external onlyFundraiser returns (bool) { cnyEthRate = rate; CnyEthRateUpdated(cnyEthRate); return true; } /** * @dev Update the CNY/BTC rate to record purchases in CNY */ function updateCnyBtcRate(uint256 rate) external onlyFundraiser returns (bool) { cnyBtcRate = rate; CnyBtcRateUpdated(cnyBtcRate); return true; } /** * @dev Allow for the possibilyt for contract owner to start crowdsale */ function ownerStartsCrowdsale(uint256 timestamp) external onlyOwner { assert(startDate == 0 && block.number >= purchaseStartBlock); // overwriting startDate is not permitted and it should be after the crowdsale start block startCrowdsale(timestamp); } /** * @dev Ends crowdsale * @param timestamp Timestamp at the crowdsale ended */ function endCrowdsale(uint256 timestamp) external onlyOwner { assert(timestamp > 0 && timestamp <= now); assert(endedAt == 0); // overwriting time is not permitted endedAt = timestamp; CrowdsaleEnded(endedAt); } /** * @dev Invalidate a crowdsale purchase if something is wrong with it * @param purchaseIdx Index number of the crowdsalePurchases to invalidate */ function invalidatePurchase(uint256 purchaseIdx) external onlyOwner whenEnded tokensNotDelivered returns (bool) { CrowdsalePurchase memory purchase = crowdsalePurchases[purchaseIdx]; assert(purchase.purchaser != 0 && purchase.amount != 0); crowdsalePurchases[purchaseIdx].amount = 0; crowdsalePurchases[purchaseIdx].rawAmount = 0; invalidatedOrigPurchases[purchaseIdx] = purchase; PurchaseInvalidated(purchaseIdx); return true; } /** * @dev Amend a crowdsale purchase if something is wrong with it * @param purchaseIdx Index number of the crowdsalePurchases to invalidate * @param purchaser Address of the buyer * @param amount Purchased tokens as per the CNY rate used * @param rawAmount Purchased tokens as per the CNY rate used without the bonus * @param purchasedAt Timestamp at the purchase made * @param data Identifier as an evidence of the purchase (e.g. btc:1xyzxyz) * @param bonus bonus milestones of the purchase */ function amendPurchase( uint256 purchaseIdx, address purchaser, uint256 amount, uint256 rawAmount, uint256 purchasedAt, string data, uint256 bonus ) external onlyOwner whenEnded tokensNotDelivered returns (bool) { CrowdsalePurchase memory purchase = crowdsalePurchases[purchaseIdx]; assert(purchase.purchaser != 0 && purchase.amount != 0); amendedOrigPurchases[purchaseIdx] = purchase; crowdsalePurchases[purchaseIdx] = CrowdsalePurchase(purchaser, amount, rawAmount, purchasedAt, data, bonus); PurchaseAmended(purchaseIdx); return true; } /** * @dev Deliver tokens to purchasers according to their purchase amount in CNY */ function deliverPurchasedTokens() external onlyOwner whenEnded returns (bool) { assert(earlyPurchasesLoaded); assert(address(starbaseToken) != 0); uint256 totalAmountOfPurchasesInCny = totalRaisedAmountInCny(); // totalPreSale + totalCrowdsale for (uint256 i = numOfDeliveredCrowdsalePurchases; i < crowdsalePurchases.length && msg.gas > 200000; i++) { CrowdsalePurchase memory purchase = crowdsalePurchases[i]; if (purchase.amount == 0) { continue; // skip invalidated purchase } /* * “Value” refers to the contribution of the User: * {crowdsale_purchaser_token_amount} = * {crowdsale_token_amount} * {crowdsalePurchase_value} / {earlypurchase_value} + {crowdsale_value}. * * Example: If a User contributes during the Contribution Period 100 CNY (including applicable * Bonus, if any) and the total amount early purchases amounts to 6’000’000 CNY * and total amount raised during the Contribution Period is 30’000’000, then he will get * 347.22 STAR = 125’000’000 STAR * 100 CNY / 30’000’000 CNY + 6’000’000 CNY. */ uint256 crowdsalePurchaseValue = purchase.amount; uint256 tokenCount = SafeMath.mul(crowdsaleTokenAmount, crowdsalePurchaseValue) / totalAmountOfPurchasesInCny; numOfPurchasedTokensOnCsBy[purchase.purchaser] = SafeMath.add(numOfPurchasedTokensOnCsBy[purchase.purchaser], tokenCount); starbaseToken.allocateToCrowdsalePurchaser(purchase.purchaser, tokenCount); numOfDeliveredCrowdsalePurchases = SafeMath.add(i, 1); } for (uint256 j = numOfDeliveredEarlyPurchases; j < earlyPurchasers.length && msg.gas > 200000; j++) { address earlyPurchaser = earlyPurchasers[j]; /* * “Value” refers to the contribution of the User: * {earlypurchaser_token_amount} = * {earlypurchaser_token_amount} * ({earlypurchase_value} / {total_earlypurchase_value}) * + {crowdsale_token_amount} * ({earlypurchase_value} / {earlypurchase_value} + {crowdsale_value}). * * Example: If an Early Purchaser contributes 100 CNY (including Bonus of 20%) and the * total amount of early purchases amounts to 6’000’000 CNY and the total amount raised * during the Contribution Period is 30’000’000 CNY, then he will get 1180.55 STAR = * 50’000’000 STAR * 100 CNY / 6’000’000 CNY + 125’000’000 STAR * 100 CNY / * 30’000’000 CNY + 6’000’000 CNY */ uint256 earlyPurchaserPurchaseValue = earlyPurchasedAmountBy[earlyPurchaser]; uint256 epTokenCalculationFromEPTokenAmount = SafeMath.mul(earlyPurchaseTokenAmount, earlyPurchaserPurchaseValue) / totalAmountOfEarlyPurchases(); uint256 epTokenCalculationFromCrowdsaleTokenAmount = SafeMath.mul(crowdsaleTokenAmount, earlyPurchaserPurchaseValue) / totalAmountOfPurchasesInCny; uint256 epTokenCount = SafeMath.add(epTokenCalculationFromEPTokenAmount, epTokenCalculationFromCrowdsaleTokenAmount); numOfPurchasedTokensOnEpBy[earlyPurchaser] = SafeMath.add(numOfPurchasedTokensOnEpBy[earlyPurchaser], epTokenCount); starbaseToken.allocateToCrowdsalePurchaser(earlyPurchaser, epTokenCount); numOfDeliveredEarlyPurchases = SafeMath.add(j, 1); } return true; } /** * @dev Load early purchases from the contract keeps track of them */ function loadEarlyPurchases() external onlyOwner returns (bool) { if (earlyPurchasesLoaded) { return false; // all EPs have already been loaded } uint256 numOfOrigEp = starbaseEpAmendment .starbaseEarlyPurchase() .numberOfEarlyPurchases(); for (uint256 i = numOfLoadedEarlyPurchases; i < numOfOrigEp && msg.gas > 200000; i++) { if (starbaseEpAmendment.isInvalidEarlyPurchase(i)) { continue; } var (purchaser, amount,) = starbaseEpAmendment.isAmendedEarlyPurchase(i) ? starbaseEpAmendment.amendedEarlyPurchases(i) : starbaseEpAmendment.earlyPurchases(i); if (amount > 0) { if (earlyPurchasedAmountBy[purchaser] == 0) { earlyPurchasers.push(purchaser); } // each early purchaser receives 20% bonus uint256 bonus = SafeMath.mul(amount, 20) / 100; uint256 amountWithBonus = SafeMath.add(amount, bonus); earlyPurchasedAmountBy[purchaser] += amountWithBonus; } } numOfLoadedEarlyPurchases += i; assert(numOfLoadedEarlyPurchases <= numOfOrigEp); if (numOfLoadedEarlyPurchases == numOfOrigEp) { earlyPurchasesLoaded = true; // enable the flag } return true; } /** * @dev Set qualified crowdsale partner i.e. Bitcoin Suisse address * @param _qualifiedPartner Address of the qualified partner that can purchase during crowdsale * @param _amountCap Ether value which partner is able to contribute * @param _commissionFeePercentage Integer that represents the fee to pay qualified partner 5 is 5% */ function setQualifiedPartner(address _qualifiedPartner, uint256 _amountCap, uint256 _commissionFeePercentage) external onlyOwner { assert(!qualifiedPartners[_qualifiedPartner].bonaFide); qualifiedPartners[_qualifiedPartner].bonaFide = true; qualifiedPartners[_qualifiedPartner].amountCap = _amountCap; qualifiedPartners[_qualifiedPartner].commissionFeePercentage = _commissionFeePercentage; QualifiedPartnerAddress(_qualifiedPartner); } /** * @dev Remove address from qualified partners list. * @param _qualifiedPartner Address to be removed from the list. */ function unlistQualifiedPartner(address _qualifiedPartner) external onlyOwner { assert(qualifiedPartners[_qualifiedPartner].bonaFide); qualifiedPartners[_qualifiedPartner].bonaFide = false; } /** * @dev Update whitelisted address amount allowed to raise during the presale. * @param _qualifiedPartner Qualified Partner address to be updated. * @param _amountCap Amount that the address is able to raise during the presale. */ function updateQualifiedPartnerCapAmount(address _qualifiedPartner, uint256 _amountCap) external onlyOwner { assert(qualifiedPartners[_qualifiedPartner].bonaFide); qualifiedPartners[_qualifiedPartner].amountCap = _amountCap; } /** * Public functions */ /** * @dev Returns boolean for whether crowdsale has ended */ function isEnded() constant public returns (bool) { return (endedAt > 0 && endedAt <= now); } /** * @dev Returns number of purchases to date. */ function numOfPurchases() constant public returns (uint256) { return crowdsalePurchases.length; } /** * @dev Calculates total amount of tokens purchased includes bonus tokens. */ function totalAmountOfCrowdsalePurchases() constant public returns (uint256 amount) { for (uint256 i; i < crowdsalePurchases.length; i++) { amount = SafeMath.add(amount, crowdsalePurchases[i].amount); } } /** * @dev Calculates total amount of tokens purchased without bonus conversion. */ function totalAmountOfCrowdsalePurchasesWithoutBonus() constant public returns (uint256 amount) { for (uint256 i; i < crowdsalePurchases.length; i++) { amount = SafeMath.add(amount, crowdsalePurchases[i].rawAmount); } } /** * @dev Returns total raised amount in CNY (includes EP) and bonuses */ function totalRaisedAmountInCny() constant public returns (uint256) { return SafeMath.add(totalAmountOfEarlyPurchases(), totalAmountOfCrowdsalePurchases()); } /** * @dev Returns total amount of early purchases in CNY */ function totalAmountOfEarlyPurchases() constant public returns(uint256) { return starbaseEpAmendment.totalAmountOfEarlyPurchases(); } /** * @dev Allows qualified crowdsale partner to purchase Star Tokens */ function purchaseAsQualifiedPartner() payable public rateIsSet(cnyEthRate) returns (bool) { require(qualifiedPartners[msg.sender].bonaFide); qualifiedPartners[msg.sender].amountRaised = SafeMath.add(msg.value, qualifiedPartners[msg.sender].amountRaised); assert(qualifiedPartners[msg.sender].amountRaised <= qualifiedPartners[msg.sender].amountCap); uint256 bonusTier = 30; // Pre sale purchasers get 30 percent bonus uint256 rawAmount = SafeMath.mul(msg.value, cnyEthRate) / 1e18; uint amount = recordPurchase(msg.sender, rawAmount, now, '', bonusTier); if (qualifiedPartners[msg.sender].commissionFeePercentage > 0) { sendQualifiedPartnerCommissionFee(msg.sender, msg.value); } StarBasePurchasedWithEth(msg.sender, amount, rawAmount, cnyEthRate, bonusTier); return true; } /** * @dev Allows user to purchase STAR tokens with Ether */ function purchaseWithEth() payable public minInvestment whenNotEnded rateIsSet(cnyEthRate) returns (bool) { require(purchaseStartBlock > 0 && block.number >= purchaseStartBlock); if (startDate == 0) { startCrowdsale(block.timestamp); } uint256 bonusTier = getBonusTier(); uint256 rawAmount = SafeMath.mul(msg.value, cnyEthRate) / 1e18; uint amount = recordPurchase(msg.sender, rawAmount, now, '', bonusTier); StarBasePurchasedWithEth(msg.sender, amount, rawAmount, cnyEthRate, bonusTier); return true; } /** * Internal functions */ /** * @dev Initializes Starbase crowdsale */ function startCrowdsale(uint256 timestamp) internal { startDate = timestamp; // set token bonus milestones firstBonusSalesEnds = startDate + 7 days; // 1. 1st ~ 7th day secondBonusSalesEnds = firstBonusSalesEnds + 14 days; // 2. 8th ~ 21st day thirdBonusSalesEnds = secondBonusSalesEnds + 14 days; // 3. 22nd ~ 35th day fourthBonusSalesEnds = thirdBonusSalesEnds + 7 days; // 4. 36th ~ 42nd day fifthBonusSalesEnds = fourthBonusSalesEnds + 3 days; // 5. 43rd ~ 45th day // extended sales bonus milestones firstExtendedBonusSalesEnds = fifthBonusSalesEnds + 3 days; // 1. 46th ~ 48th day secondExtendedBonusSalesEnds = firstExtendedBonusSalesEnds + 3 days; // 2. 49th ~ 51st day thirdExtendedBonusSalesEnds = secondExtendedBonusSalesEnds + 3 days; // 3. 52nd ~ 54th day fourthExtendedBonusSalesEnds = thirdExtendedBonusSalesEnds + 3 days; // 4. 55th ~ 57th day fifthExtendedBonusSalesEnds = fourthExtendedBonusSalesEnds + 3 days; // 5. 58th ~ 60th day sixthExtendedBonusSalesEnds = fifthExtendedBonusSalesEnds + 60 days; // 6. 61st ~ 120th day } /** * @dev Abstract record of a purchase to Tokens * @param purchaser Address of the buyer * @param rawAmount Amount in CNY as per the CNY/ETH rate used * @param timestamp Timestamp at the purchase made * @param data Identifier as an evidence of the purchase (e.g. btc:1xyzxyz) * @param bonusTier bonus milestones of the purchase */ function recordPurchase( address purchaser, uint256 rawAmount, uint256 timestamp, string data, uint256 bonusTier ) internal returns(uint256 amount) { amount = rawAmount; // amount to check reach of max cap. it does not care for bonus tokens here // presale transfers which occurs before the crowdsale ignores the crowdsale hard cap if (block.number >= purchaseStartBlock) { assert(totalAmountOfCrowdsalePurchasesWithoutBonus() <= MAX_CROWDSALE_CAP); uint256 crowdsaleTotalAmountAfterPurchase = SafeMath.add(totalAmountOfCrowdsalePurchasesWithoutBonus(), amount); // check whether purchase goes over the cap and send the difference back to the purchaser. if (crowdsaleTotalAmountAfterPurchase > MAX_CROWDSALE_CAP) { uint256 difference = SafeMath.sub(crowdsaleTotalAmountAfterPurchase, MAX_CROWDSALE_CAP); uint256 ethValueToReturn = SafeMath.mul(difference, 1e18) / cnyEthRate; purchaser.transfer(ethValueToReturn); amount = SafeMath.sub(amount, difference); rawAmount = amount; } } uint256 covertedAmountwWithBonus = SafeMath.mul(amount, bonusTier) / 100; amount = SafeMath.add(amount, covertedAmountwWithBonus); // at this point amount bonus is calculated CrowdsalePurchase memory purchase = CrowdsalePurchase(purchaser, amount, rawAmount, timestamp, data, bonusTier); crowdsalePurchases.push(purchase); return amount; } /** * @dev Fetchs Bonus tier percentage per bonus milestones */ function getBonusTier() internal returns (uint256) { bool firstBonusSalesPeriod = now >= startDate && now <= firstBonusSalesEnds; // 1st ~ 7th day get 20% bonus bool secondBonusSalesPeriod = now > firstBonusSalesEnds && now <= secondBonusSalesEnds; // 8th ~ 21st day get 15% bonus bool thirdBonusSalesPeriod = now > secondBonusSalesEnds && now <= thirdBonusSalesEnds; // 22nd ~ 35th day get 10% bonus bool fourthBonusSalesPeriod = now > thirdBonusSalesEnds && now <= fourthBonusSalesEnds; // 36th ~ 42nd day get 5% bonus bool fifthBonusSalesPeriod = now > fourthBonusSalesEnds && now <= fifthBonusSalesEnds; // 43rd and 45th day get 0% bonus // extended bonus sales bool firstExtendedBonusSalesPeriod = now > fifthBonusSalesEnds && now <= firstExtendedBonusSalesEnds; // extended sales 46th ~ 48th day get 20% bonus bool secondExtendedBonusSalesPeriod = now > firstExtendedBonusSalesEnds && now <= secondExtendedBonusSalesEnds; // 49th ~ 51st 15% bonus bool thirdExtendedBonusSalesPeriod = now > secondExtendedBonusSalesEnds && now <= thirdExtendedBonusSalesEnds; // 52nd ~ 54th day get 10% bonus bool fourthExtendedBonusSalesPeriod = now > thirdExtendedBonusSalesEnds && now <= fourthExtendedBonusSalesEnds; // 55th ~ 57th day day get 5% bonus bool fifthExtendedBonusSalesPeriod = now > fourthExtendedBonusSalesEnds && now <= fifthExtendedBonusSalesEnds; // 58th ~ 60th day get 0% bonus bool sixthExtendedBonusSalesPeriod = now > fifthExtendedBonusSalesEnds && now <= sixthExtendedBonusSalesEnds; // 61st ~ 120th day get {number_of_days} - 60 * 1% bonus if (firstBonusSalesPeriod || firstExtendedBonusSalesPeriod) return 20; if (secondBonusSalesPeriod || secondExtendedBonusSalesPeriod) return 15; if (thirdBonusSalesPeriod || thirdExtendedBonusSalesPeriod) return 10; if (fourthBonusSalesPeriod || fourthExtendedBonusSalesPeriod) return 5; if (fifthBonusSalesPeriod || fifthExtendedBonusSalesPeriod) return 0; if (sixthExtendedBonusSalesPeriod) { uint256 DAY_IN_SECONDS = 86400; uint256 secondsSinceStartDate = SafeMath.sub(now, startDate); uint256 numberOfDays = secondsSinceStartDate / DAY_IN_SECONDS; return SafeMath.sub(numberOfDays, 60); } } /** * @dev Fetchs Bonus tier percentage per bonus milestones * @dev qualifiedPartner Address of partners that participated in pre sale * @dev amountSent Value sent by qualified partner */ function sendQualifiedPartnerCommissionFee(address qualifiedPartner, uint256 amountSent) internal { //calculate the commission fee to send to qualified partner uint256 commissionFeePercentageCalculationAmount = SafeMath.mul(amountSent, qualifiedPartners[qualifiedPartner].commissionFeePercentage) / 100; // send commission fee amount qualifiedPartner.transfer(commissionFeePercentageCalculationAmount); } /** * @dev redirectToPurchase Redirect to adequate purchase function within the smart contract */ function redirectToPurchase() internal { if (block.number < purchaseStartBlock) { purchaseAsQualifiedPartner(); } else { purchaseWithEth(); } } }
* @dev Returns number of early purchases/
function numberOfEarlyPurchases() external constant noEther returns (uint256) { return normalizedEarlyPurchases().length; }
12,901,610
[ 1, 1356, 1300, 434, 11646, 5405, 343, 3304, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7922, 41, 20279, 10262, 343, 3304, 1435, 203, 3639, 3903, 203, 3639, 5381, 203, 3639, 1158, 41, 1136, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 5640, 41, 20279, 10262, 343, 3304, 7675, 2469, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /** * @title MyFriendships * @dev A contract for managing one's friendships. */ contract MyFriendships { address public me; uint public numberOfFriends; address public latestFriend; mapping(address => bool) myFriends; /** * @dev Create a contract to keep track of my friendships. */ function MyFriendships() public { me = msg.sender; } /** * @dev Start an exciting new friendship with me. */ function becomeFriendsWithMe () public { require(msg.sender != me); // I won't be friends with myself. myFriends[msg.sender] = true; latestFriend = msg.sender; numberOfFriends++; } /** * @dev Am I friends with this address? */ function friendsWith (address addr) public view returns (bool) { return myFriends[addr]; } }
* @dev Am I friends with this address?/
function friendsWith (address addr) public view returns (bool) { return myFriends[addr]; }
13,047,889
[ 1, 9864, 467, 284, 22259, 598, 333, 1758, 35, 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, 284, 22259, 1190, 261, 2867, 3091, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 3399, 42, 22259, 63, 4793, 15533, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x30993BD1d103Ac3d163797dc04aAFaa1fDd1069C/sources/browser/CompositeVaults/CompositeVaultBBridgeUsdc.sol
No rebalance implementation for lower fees and faster swaps Check that no mint has been made in the same block from the same EOA
function withdrawFor( address _account, uint256 _shares, address _output, uint256 _min_output_amount ) public override _non_reentrant_ returns (uint256 _output_amount) { require(keccak256(abi.encodePacked(tx.origin, block.number)) != _minterBlock, "REENTR MINT-BURN"); _output_amount = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 _withdrawalProtectionFee = vaultMaster.withdrawalProtectionFee(); if (_withdrawalProtectionFee > 0) { uint256 _withdrawalProtection = _output_amount.mul(_withdrawalProtectionFee).div(10000); _output_amount = _output_amount.sub(_withdrawalProtection); } if (b < _output_amount) { uint256 _toWithdraw = _output_amount.sub(b); uint256 _withdrawFee = IController(controller).withdraw(_toWithdraw); uint256 _after = basedToken.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _toWithdraw) { _output_amount = b.add(_diff); } if (_withdrawFee > 0) { _output_amount = _output_amount.sub(_withdrawFee, "_output_amount < _withdrawFee"); } } if (_output == address(basedToken)) { require(_output_amount >= _min_output_amount, "slippage"); basedToken.safeTransfer(_account, _output_amount); basedToken.safeTransfer(address(basedConverter), _output_amount); uint256 _received = basedConverter.convert(address(basedToken), _output, address(this)); require(_received >= _min_output_amount, "slippage"); IERC20(_output).safeTransfer(_account, _received); } }
9,690,473
[ 1, 2279, 283, 12296, 4471, 364, 2612, 1656, 281, 471, 12063, 1352, 6679, 2073, 716, 1158, 312, 474, 711, 2118, 7165, 316, 326, 1967, 1203, 628, 326, 1967, 512, 28202, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1290, 12, 203, 3639, 1758, 389, 4631, 16, 203, 3639, 2254, 5034, 389, 30720, 16, 203, 3639, 1758, 389, 2844, 16, 203, 3639, 2254, 5034, 389, 1154, 67, 2844, 67, 8949, 203, 565, 262, 1071, 3849, 389, 5836, 67, 2842, 313, 970, 67, 1135, 261, 11890, 5034, 389, 2844, 67, 8949, 13, 288, 203, 3639, 2583, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 978, 18, 10012, 16, 1203, 18, 2696, 3719, 480, 389, 1154, 387, 1768, 16, 315, 862, 2222, 54, 490, 3217, 17, 38, 8521, 8863, 203, 203, 3639, 389, 2844, 67, 8949, 273, 261, 12296, 7675, 16411, 24899, 30720, 13, 2934, 2892, 12, 4963, 3088, 1283, 10663, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 389, 30720, 1769, 203, 203, 3639, 2254, 5034, 389, 1918, 9446, 287, 16938, 14667, 273, 9229, 7786, 18, 1918, 9446, 287, 16938, 14667, 5621, 203, 3639, 309, 261, 67, 1918, 9446, 287, 16938, 14667, 405, 374, 13, 288, 203, 5411, 2254, 5034, 389, 1918, 9446, 287, 16938, 273, 389, 2844, 67, 8949, 18, 16411, 24899, 1918, 9446, 287, 16938, 14667, 2934, 2892, 12, 23899, 1769, 203, 5411, 389, 2844, 67, 8949, 273, 389, 2844, 67, 8949, 18, 1717, 24899, 1918, 9446, 287, 16938, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 70, 411, 389, 2844, 67, 8949, 13, 288, 203, 5411, 2254, 5034, 389, 869, 1190, 9446, 273, 389, 2844, 67, 8949, 18, 1717, 12, 70, 1769, 203, 5411, 2254, 5034, 389, 1918, 9446, 14667, 2 ]
//Address: 0x1ffdbcecea31ea4f8a659f6ba0dc314983db872d //Contract name: ClientsHandler //Balance: 0 Ether //Verification Date: 4/30/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.21; /** * @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); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ManageableContract is Ownable { mapping (address => bool) internal pf_manager; // SP maganer, Artificial Intelligence AI in the fuature uint256[] internal pf_m_count; // clients tasks counter mapping (address => bool) internal performers; uint256[] internal pf_count; // clients tasks counter mapping (address => bool) internal cr_manager; // client relations manager CR-Manager uint256[] internal cr_count; // clients tasks counter mapping (address => bool) internal clients; uint256[] internal cli_count; // clients tasks counter // MODIFIERS modifier is_cli() { require(clients[msg.sender] == true); _; } modifier is_no_cli() { require(clients[msg.sender] == true); _; } modifier is_cr_mng() { require(cr_manager[msg.sender] == true); _; } modifier is_pfm() { require(performers[msg.sender] == true); _; } modifier is_pf_mng() { require(pf_manager[msg.sender] == true); _; } modifier is_cli_trust() { require( owner == msg.sender || cr_manager[msg.sender] == true ); _; } modifier is_cli_or_trust() { require( clients[msg.sender] == true || owner == msg.sender || cr_manager[msg.sender] == true || performers[msg.sender] == true || pf_manager[msg.sender] == true ); _; } modifier is_trust() { require( owner == msg.sender || cr_manager[msg.sender] == true || performers[msg.sender] == true || pf_manager[msg.sender] == true ); _; } function setPFManager(address _manager) public onlyOwner returns (bool, address) { pf_manager[_manager] = true; pf_m_count.push(1); return (true, _manager); } function setPerformer(address _to) public onlyOwner returns (bool, address) { performers[_to] = true; pf_count.push(1); return (true, _to); } function setCRManager(address _manager) public onlyOwner returns (bool, address) { cr_manager[_manager] = true; cr_count.push(1); return (true, _manager); } /** get client task length */ function countPerformers() public view returns (uint256) { return pf_m_count.length; } /** get client task length */ function countPerfManagers() public view returns (uint256) { return pf_count.length; } /** get client task length */ function countCliManagers() public view returns (uint256) { return cr_count.length; } /** get client task length */ function countCliTasks() public view returns (uint256) { return cli_count.length; } } contract Converter { function bytes32ToBytes(bytes32 data) internal pure returns (bytes) { uint i = 0; while (i < 32 && uint(data[i]) != 0) { ++i; } bytes memory result = new bytes(i); i = 0; while (i < 32 && data[i] != 0) { result[i] = data[i]; ++i; } return result; } /** @dev concat bytes array */ function bytes32ArrayToString(bytes32[] data) internal pure returns (string) { bytes memory bytesString = new bytes(data.length * 32); uint urlLength; for (uint i=0; i<data.length; i++) { for (uint j=0; j<32; j++) { byte char = byte(bytes32(uint(data[i]) * 2 ** (8 * j))); if (char != 0) { bytesString[urlLength] = char; urlLength += 1; } } } bytes memory bytesStringTrimmed = new bytes(urlLength); for (i=0; i<urlLength; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } function uintToBytes(uint v) internal pure returns (bytes32 ret) { if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } return ret; } function addressToBytes(address a) internal pure returns (bytes32 b){ assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } function bytesToBytes32(bytes b, uint offset) internal pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } function bytes32ToString(bytes32 x) internal pure returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } //Только чтобы с сайта мечты/задачи и статус исполнителя писался в смарт контракт /** warning add divide rule beatween accepted tasks and wiev rules for */ contract ClientsHandler is ManageableContract, Converter { function ClientsHandler() public { setPFManager(owner); setCRManager(owner); } string name = "Clients Handler"; string descibe = "Clients data storage, contain methods for their obtaining and auditing"; string version = "0.28"; // @dev defaul validtor values uint256 dml = 3; uint256 dmxl = 100; uint256 tml = 3; uint256 tmxl = 1000; struct DreamStructData { string hashId; string dream; string target; bool isDream; bool hasPerformer; address performer; } struct DreamStruct { bool isClient; uint256[] key; } mapping(address => mapping(uint256 => DreamStructData)) internal DSData; mapping(address => DreamStruct) internal DStructs; address[] public clientsList; //count users struct DreamStructDataP { bool isValid; address client; uint256 client_id; } struct DreamStructP { bool isPerformer; uint256[] key; } mapping(address => mapping(uint256 => DreamStructDataP)) internal DSDataP; mapping(address => DreamStructP) internal DStructsP; address[] public performerList; //count users function watchPreferersTasks(address entityAddress, uint256 _id) public view { DSDataP[entityAddress][_id]; } /** @dev return data of client's dream by id */ function getDStructData(address _who, uint256 _dream_id) public view is_cli_or_trust returns(string, string) { require(DSData[_who][_dream_id].isDream == true); return ( DSData[_who][_dream_id].dream, DSData[_who][_dream_id].target ); } function isClient(address entityAddress) public constant returns(bool isIndeed) { return DStructs[entityAddress].isClient; } function countClients() public constant returns(uint256 cCount) { return clientsList.length; } function countAllCliDrm() public constant returns(uint256 acdCount) { uint256 l = countClients(); uint256 r = 0; for(uint256 i=0; i<l; i++) { r += countCliDreams(clientsList[i]); } return r; } function countCliDreams(address _addr) public view returns(uint256 cdCount) { return DStructs[_addr].key.length; } function countPerfClients(address _addr) public view returns(uint256 cdpCount) { return DStructsP[_addr].key.length; } function findAllCliWithPendingTask(address _addr) public returns(address[] noPerform) { uint256 l = countClients(); address[] storage r; for(uint256 i=0; i<l; i++) { uint256 ll = countCliDreams(clientsList[i]); for(uint256 ii=0; ii<ll; ii++) { uint256 li = ii + 1; if(DSData[_addr][li].hasPerformer == false) { r.push(_addr); } } } return r; } /** @dev by the address of client set performer for pending task */ function findCliPendTAndSetPrfm(address _addr, address _performer) public returns(uint256) { uint256 l = countCliDreams(_addr); for(uint256 i=0; i<l; i++) { uint256 li = i + 1; if(DSData[_addr][li].hasPerformer == false) { DSData[_addr][li].hasPerformer = true; DSData[_addr][li].performer = _performer; uint256 pLen = countPerfClients(_performer); uint256 iLen = pLen + 1; DSDataP[_performer][iLen].client = _addr; DSDataP[_performer][iLen].client_id = li; DSDataP[_performer][iLen].isValid = true; return performerList.push(_addr); } } } /** @dev change perferfer for uncomplited task if he is fail */ function changePrefererForTask(address _addr, uint256 _id, address _performer) public is_pf_mng returns(bool) { require(performers[_performer] == true); if(DSData[_addr][_id].isDream == true) { DSData[_addr][_id].hasPerformer = true; DSData[_addr][_id].performer = _performer; return true; } } function setValidatorForND( uint256 dream_min_len, uint256 target_min_len, uint256 dream_max_len, uint256 target_max_len ) public onlyOwner returns (bool) { dml = dream_min_len; dmxl = dream_max_len; tml = target_min_len; tmxl = target_max_len; return true; } modifier validatorD(string dream, string target) { require( (bytes(dream).length > dml) && (bytes(dream).length <= dmxl) && (bytes(target).length > tml) && (bytes(target).length <= tmxl) ); _; } /** @dev allow for all who want stand client */ function newDream(address entityAddress, string dream, string target) public validatorD(dream, target) returns (uint256 rowNumber) { clients[entityAddress] = true; DStructs[entityAddress].key.push(1); DStructs[entityAddress].isClient = true; uint256 cliLen = countCliDreams(entityAddress); uint256 incLen = cliLen + 1; DSData[entityAddress][incLen].dream = dream; DSData[entityAddress][incLen].target = target; DSData[entityAddress][incLen].isDream = true; return clientsList.push(entityAddress); } /** @dev allow for all who want stand client */ function updateDream(address entityAddress, string dream, string target) public is_cli_trust validatorD(dream, target) returns (bool success) { //DStructs[entityAddress].key.push(1); uint256 cliLen = countCliDreams(entityAddress); uint256 incLen = cliLen + 1; DSData[entityAddress][incLen].dream = dream; DSData[entityAddress][incLen].target = target; DSData[entityAddress][incLen].isDream = true; return true; } /* function makeUnicTaskHashId(address who) internal view returns (bytes32) { string memory d = bytes32ToString(uintToBytes(block.difficulty)); string memory bh = bytes32ToString(block.blockhash(block.number)); string memory t = bytes32ToString(uintToBytes(block.timestamp)); string memory w = bytes32ToString(addressToBytes(who)); string memory s1 = " ".toSlice().concat(d.toSlice()); string memory sb1 = string(bh.toSlice().concat(s1.toSlice())); string memory s2 = " ".toSlice().concat(sb1.toSlice()); string memory sb2 = string(t.toSlice().concat(s2.toSlice())); string memory s3 = " ".toSlice().concat(sb2.toSlice()); string memory sb3 = string(w.toSlice().concat(s3.toSlice())); return keccak256(sb3); }*/ }
* get client task length */
function countPerfManagers() public view returns (uint256) { return pf_count.length; }
898,069
[ 1, 588, 1004, 1562, 769, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1056, 22016, 17570, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 10811, 67, 1883, 18, 2469, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // // This contract handles swapping to and from PlatinumNugget, LuckySwap's staking token. contract AlchemyBench is ERC20("AlchemyBench", "PLAN"){ using SafeMath for uint256; IERC20 public goldnugget; // Define the GoldNugget token contract constructor(IERC20 _goldnugget) public { goldnugget = _goldnugget; } // Enter the alchemybench. Pay some GOLNs. Earn some shares. // Locks GoldNugget and mints PlatinumNugget function enter(uint256 _amount) public { // Gets the amount of GoldNugget locked in the contract uint256 totalGoldNugget = goldnugget.balanceOf(address(this)); // Gets the amount of PlatinumNugget in existence uint256 totalShares = totalSupply(); // If no PlatinumNugget exists, mint it 1:1 to the amount put in if (totalShares == 0 || totalGoldNugget == 0) { _mint(msg.sender, _amount); } // Calculate and mint the amount of PlatinumNugget the GoldNugget is worth. The ratio will change overtime, as PlatinumNugget is burned/minted and GoldNugget deposited + gained from fees / withdrawn. else { uint256 what = _amount.mul(totalShares).div(totalGoldNugget); _mint(msg.sender, what); } // Lock the GoldNugget in the contract goldnugget.transferFrom(msg.sender, address(this), _amount); } // Leave the alchemybench. Claim back your GOLNs. // Unlocks the staked + gained GoldNugget and burns PlatinumNugget function leave(uint256 _share) public { // Gets the amount of PlatinumNugget in existence uint256 totalShares = totalSupply(); // Calculates the amount of GoldNugget the PlatinumNugget is worth uint256 what = _share.mul(goldnugget.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); goldnugget.transfer(msg.sender, what); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // XXX: pragma solidity ^0.5.16; pragma solidity 0.6.12; // XXX: import "./SafeMath.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Router01.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/libraries/UniswapV2Library.sol"; // Ingot helps your migrate your existing Uniswap LP tokens to LuckySwap LP ones contract Ingot { using SafeERC20 for IERC20; IUniswapV2Router01 public oldRouter; IUniswapV2Router01 public router; constructor(IUniswapV2Router01 _oldRouter, IUniswapV2Router01 _router) public { oldRouter = _oldRouter; router = _router; } function migrateWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB)); pair.permit(msg.sender, address(this), liquidity, deadline, v, r, s); migrate(tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline); } // msg.sender should have approved 'liquidity' amount of LP token of 'tokenA' and 'tokenB' function migrate( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) public { require(deadline >= block.timestamp, 'LuckySwap: EXPIRED'); // Remove liquidity from the old router with permit (uint256 amountA, uint256 amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline ); // Add liquidity to the new router (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB); // Send remaining tokens to msg.sender if (amountA > pooledAmountA) { IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA); } if (amountB > pooledAmountB) { IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB); } } function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB)); pair.transferFrom(msg.sender, address(pair), liquidity); (uint256 amount0, uint256 amount1) = pair.burn(address(this)); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'Ingot: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'Ingot: INSUFFICIENT_B_AMOUNT'); } // calculates the CREATE2 address for a pair without making any external calls function pairForOldRouter(address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', oldRouter.factory(), keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint amountA, uint amountB) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired); address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB); IERC20(tokenA).safeTransfer(pair, amountA); IERC20(tokenB).safeTransfer(pair, amountB); IUniswapV2Pair(pair).mint(msg.sender); } function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { // create the pair if it doesn't exist yet IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import '../interfaces/IUniswapV2Pair.sol'; import "./SafeMath.sol"; library UniswapV2Library { using SafeMathUniswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './libraries/UniswapV2Library.sol'; import './libraries/SafeMath.sol'; import './libraries/TransferHelper.sol'; import './interfaces/IUniswapV2Router02.sol'; import './interfaces/IUniswapV2Factory.sol'; import './interfaces/IERC20.sol'; import './interfaces/IWETH.sol'; contract UniswapV2Router02 is IUniswapV2Router02 { using SafeMathUniswap for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UniswapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IUniswapV2Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return UniswapV2Library.getAmountsIn(factory, amountOut, path); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './UniswapV2ERC20.sol'; import './libraries/Math.sol'; import './libraries/UQ112x112.sol'; import './interfaces/IERC20.sol'; import './interfaces/IUniswapV2Factory.sol'; import './interfaces/IUniswapV2Callee.sol'; interface IMigrator { // Return the desired amount of liquidity token that the migrator wants. function desiredLiquidity() external view returns (uint256); } contract UniswapV2Pair is UniswapV2ERC20 { using SafeMathUniswap for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'UniswapV2: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IUniswapV2Factory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20Uniswap(token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { address migrator = IUniswapV2Factory(factory).migrator(); if (msg.sender == migrator) { liquidity = IMigrator(migrator).desiredLiquidity(); require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); } else { require(migrator == address(0), "Must not have migrator"); liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './libraries/SafeMath.sol'; contract UniswapV2ERC20 { using SafeMathUniswap for uint; string public constant name = 'LuckySwap LP Token'; string public constant symbol = 'SLP'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../uniswapv2/UniswapV2Pair.sol"; contract LuckySwapPairMock is UniswapV2Pair { constructor() public UniswapV2Pair() {} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libraries/SafeMath.sol"; import "./libraries/SafeERC20.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./Ownable.sol"; interface IAlpineWithdraw { function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); } interface IGoldVeinWithdrawFee { function asset() external view returns (address); function balanceOf(address account) external view returns (uint256); function withdrawFees() external; function removeAsset(address to, uint256 fraction) external returns (uint256 share); } // SmelterGoldVein is GoldMiner's left hand and kinda a wizard. He can cook up GoldNugget from pretty much anything! // This contract handles "serving up" rewards for PlatinumNugget holders by trading tokens collected from Gold Vein fees for GoldNugget. contract SmelterGoldVein is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Factory private immutable factory; //0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac address private immutable alchemybench; //0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272 IAlpineWithdraw private immutable alPine; //0xF5BCE5077908a1b7370B9ae04AdC565EBd643966 address private immutable goldnugget; //0xc6D69475f115F61B1e8C4e78c20C49201c869DB4 address private immutable weth; //0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 bytes32 private immutable pairCodeHash; //0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303 mapping(address => address) private _bridges; event LogBridgeSet(address indexed token, address indexed bridge); event LogConvert( address indexed server, address indexed token0, uint256 amount0, uint256 amountALP, uint256 amountGOLN ); constructor( IUniswapV2Factory _factory, address _alchemybench, IAlpineWithdraw _alPine, address _goldnugget, address _weth, bytes32 _pairCodeHash ) public { factory = _factory; alchemybench = _alchemybench; alPine = _alPine; goldnugget = _goldnugget; weth = _weth; pairCodeHash = _pairCodeHash; } function setBridge(address token, address bridge) external onlyOwner { // Checks require( token != goldnugget && token != weth && token != bridge, "Smelter: Invalid bridge" ); // Effects _bridges[token] = bridge; emit LogBridgeSet(token, bridge); } modifier onlyEOA() { // Try to make flash-loan exploit harder to do by only allowing externally-owned addresses. require(msg.sender == tx.origin, "Smelter: Must use EOA"); _; } function convert(IGoldVeinWithdrawFee goldveinPair) external onlyEOA { _convert(goldveinPair); } function convertMultiple(IGoldVeinWithdrawFee[] calldata goldveinPair) external onlyEOA { for (uint256 i = 0; i < goldveinPair.length; i++) { _convert(goldveinPair[i]); } } function _convert(IGoldVeinWithdrawFee goldveinPair) private { // update Gold Vein fees for this Smelter contract (`feeTo`) goldveinPair.withdrawFees(); // convert updated Gold Vein balance to Alp shares uint256 alpShares = goldveinPair.removeAsset(address(this), goldveinPair.balanceOf(address(this))); // convert Alp shares to underlying Gold Vein asset (`token0`) balance (`amount0`) for Smelter address token0 = goldveinPair.asset(); (uint256 amount0, ) = alPine.withdraw(IERC20(token0), address(this), address(this), 0, alpShares); emit LogConvert( msg.sender, token0, amount0, alpShares, _convertStep(token0, amount0) ); } function _convertStep(address token0, uint256 amount0) private returns (uint256 goldnuggetOut) { if (token0 == goldnugget) { IERC20(token0).safeTransfer(alchemybench, amount0); goldnuggetOut = amount0; } else if (token0 == weth) { goldnuggetOut = _swap(token0, goldnugget, amount0, alchemybench); } else { address bridge = _bridges[token0]; if (bridge == address(0)) { bridge = weth; } uint256 amountOut = _swap(token0, bridge, amount0, address(this)); goldnuggetOut = _convertStep(bridge, amountOut); } } function _swap( address fromToken, address toToken, uint256 amountIn, address to ) private returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); IUniswapV2Pair pair = IUniswapV2Pair( uint256( keccak256(abi.encodePacked(hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, ""); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // a library for performing overflow-safe math, updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a + b) >= b, "SafeMath: Add Overflow");} function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {require((c = a - b) <= a, "SafeMath: Underflow");} function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {require(b == 0 || (c = a * b)/b == a, "SafeMath: Mul Overflow");} function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "SafeMath: uint128 Overflow"); c = uint128(a); } } library SafeMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a + b) >= b, "SafeMath: Add Overflow");} function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {require((c = a - b) <= a, "SafeMath: Underflow");} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IERC20.sol"; library SafeERC20 { function safeSymbol(IERC20 token) internal view returns(string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns(string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) public view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer(IERC20 token, address to, uint256 amount) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed"); } function safeTransferFrom(IERC20 token, address from, uint256 amount) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed"); } } // SPDX-License-Identifier: MIT // Audit on 5-Jan-2021 by Keno and BoringCrypto // P1 - P3: OK pragma solidity 0.6.12; // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto // T1 - T4: OK contract OwnableData { // V1 - V5: OK address public owner; // V1 - V5: OK address public pendingOwner; } // T1 - T4: OK contract Ownable is OwnableData { // E1: OK event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } // F1 - F9: OK // C1 - C21: OK function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; } else { // Effects pendingOwner = newOwner; } } // F1 - F9: OK // C1 - C21: OK function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } // M1 - M5: OK // C1 - C21: OK modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // EIP 2612 function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT // P1 - P3: OK pragma solidity 0.6.12; import "./libraries/SafeMath.sol"; import "./libraries/SafeERC20.sol"; import "./uniswapv2/interfaces/IUniswapV2ERC20.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./Ownable.sol"; // Smelter is GoldMiner's left hand and kinda a wizard. He can cook up GoldNugget from pretty much anything! // This contract handles "serving up" rewards for PlatinumNugget holders by trading tokens collected from fees for GoldNugget. // T1 - T4: OK contract Smelter is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // V1 - V5: OK IUniswapV2Factory public immutable factory; //0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac // V1 - V5: OK address public immutable alchemybench; //0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272 // V1 - V5: OK address private immutable goldnugget; //0xc6D69475f115F61B1e8C4e78c20C49201c869DB4 // V1 - V5: OK address private immutable weth; //0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 // V1 - V5: OK mapping(address => address) internal _bridges; // E1: OK event LogBridgeSet(address indexed token, address indexed bridge); // E1: OK event LogConvert( address indexed server, address indexed token0, address indexed token1, uint256 amount0, uint256 amount1, uint256 amountGOLN ); constructor( address _factory, address _alchemybench, address _goldnugget, address _weth ) public { factory = IUniswapV2Factory(_factory); alchemybench = _alchemybench; goldnugget = _goldnugget; weth = _weth; } // F1 - F10: OK // C1 - C24: OK function bridgeFor(address token) public view returns (address bridge) { bridge = _bridges[token]; if (bridge == address(0)) { bridge = weth; } } // F1 - F10: OK // C1 - C24: OK function setBridge(address token, address bridge) external onlyOwner { // Checks require( token != goldnugget && token != weth && token != bridge, "Smelter: Invalid bridge" ); // Effects _bridges[token] = bridge; emit LogBridgeSet(token, bridge); } // M1 - M5: OK // C1 - C24: OK // C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin modifier onlyEOA() { // Try to make flash-loan exploit harder to do by only allowing externally owned addresses. require(msg.sender == tx.origin, "Smelter: must use EOA"); _; } // F1 - F10: OK // F3: _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple // F6: There is an exploit to add lots of GOLN to the alchemybench, run convert, then remove the GOLN again. // As the size of the AlchemyBench has grown, this requires large amounts of funds and isn't super profitable anymore // The onlyEOA modifier prevents this being done with a flash loan. // C1 - C24: OK function convert(address token0, address token1) external onlyEOA() { _convert(token0, token1); } // F1 - F10: OK, see convert // C1 - C24: OK // C3: Loop is under control of the caller function convertMultiple( address[] calldata token0, address[] calldata token1 ) external onlyEOA() { // TODO: This can be optimized a fair bit, but this is safer and simpler for now uint256 len = token0.length; for (uint256 i = 0; i < len; i++) { _convert(token0[i], token1[i]); } } // F1 - F10: OK // C1- C24: OK function _convert(address token0, address token1) internal { // Interactions // S1 - S4: OK IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1)); require(address(pair) != address(0), "Smelter: Invalid pair"); // balanceOf: S1 - S4: OK // transfer: X1 - X5: OK IERC20(address(pair)).safeTransfer( address(pair), pair.balanceOf(address(this)) ); // X1 - X5: OK (uint256 amount0, uint256 amount1) = pair.burn(address(this)); if (token0 != pair.token0()) { (amount0, amount1) = (amount1, amount0); } emit LogConvert( msg.sender, token0, token1, amount0, amount1, _convertStep(token0, token1, amount0, amount1) ); } // F1 - F10: OK // C1 - C24: OK // All safeTransfer, _swap, _toGOLN, _convertStep: X1 - X5: OK function _convertStep( address token0, address token1, uint256 amount0, uint256 amount1 ) internal returns (uint256 goldnuggetOut) { // Interactions if (token0 == token1) { uint256 amount = amount0.add(amount1); if (token0 == goldnugget) { IERC20(goldnugget).safeTransfer(alchemybench, amount); goldnuggetOut = amount; } else if (token0 == weth) { goldnuggetOut = _toGOLN(weth, amount); } else { address bridge = bridgeFor(token0); amount = _swap(token0, bridge, amount, address(this)); goldnuggetOut = _convertStep(bridge, bridge, amount, 0); } } else if (token0 == goldnugget) { // eg. GOLN - ETH IERC20(goldnugget).safeTransfer(alchemybench, amount0); goldnuggetOut = _toGOLN(token1, amount1).add(amount0); } else if (token1 == goldnugget) { // eg. USDT - GOLN IERC20(goldnugget).safeTransfer(alchemybench, amount1); goldnuggetOut = _toGOLN(token0, amount0).add(amount1); } else if (token0 == weth) { // eg. ETH - USDC goldnuggetOut = _toGOLN( weth, _swap(token1, weth, amount1, address(this)).add(amount0) ); } else if (token1 == weth) { // eg. USDT - ETH goldnuggetOut = _toGOLN( weth, _swap(token0, weth, amount0, address(this)).add(amount1) ); } else { // eg. MIC - USDT address bridge0 = bridgeFor(token0); address bridge1 = bridgeFor(token1); if (bridge0 == token1) { // eg. MIC - USDT - and bridgeFor(MIC) = USDT goldnuggetOut = _convertStep( bridge0, token1, _swap(token0, bridge0, amount0, address(this)), amount1 ); } else if (bridge1 == token0) { // eg. WBTC - DSD - and bridgeFor(DSD) = WBTC goldnuggetOut = _convertStep( token0, bridge1, amount0, _swap(token1, bridge1, amount1, address(this)) ); } else { goldnuggetOut = _convertStep( bridge0, bridge1, // eg. USDT - DSD - and bridgeFor(DSD) = WBTC _swap(token0, bridge0, amount0, address(this)), _swap(token1, bridge1, amount1, address(this)) ); } } } // F1 - F10: OK // C1 - C24: OK // All safeTransfer, swap: X1 - X5: OK function _swap( address fromToken, address toToken, uint256 amountIn, address to ) internal returns (uint256 amountOut) { // Checks // X1 - X5: OK IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(fromToken, toToken)); require(address(pair) != address(0), "Smelter: Cannot convert"); // Interactions // X1 - X5: OK (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (fromToken == pair.token0()) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, new bytes(0)); // TODO: Add maximum slippage? } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, new bytes(0)); // TODO: Add maximum slippage? } } // F1 - F10: OK // C1 - C24: OK function _toGOLN(address token, uint256 amountIn) internal returns (uint256 amountOut) { // X1 - X5: OK amountOut = _swap(token, goldnugget, amountIn, alchemybench); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; contract Migrator { address public miner; address public oldFactory; IUniswapV2Factory public factory; uint256 public notBeforeBlock; uint256 public desiredLiquidity = uint256(-1); constructor( address _miner, address _oldFactory, IUniswapV2Factory _factory, uint256 _notBeforeBlock ) public { miner = _miner; oldFactory = _oldFactory; factory = _factory; notBeforeBlock = _notBeforeBlock; } function migrate(IUniswapV2Pair orig) public returns (IUniswapV2Pair) { require(msg.sender == miner, "not from gold miner"); require(block.number >= notBeforeBlock, "too early to migrate"); require(orig.factory() == oldFactory, "not from old factory"); address token0 = orig.token0(); address token1 = orig.token1(); IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1)); if (pair == IUniswapV2Pair(address(0))) { pair = IUniswapV2Pair(factory.createPair(token0, token1)); } uint256 lp = orig.balanceOf(msg.sender); if (lp == 0) return pair; desiredLiquidity = lp; orig.transferFrom(msg.sender, address(orig), lp); orig.burn(address(pair)); pair.mint(msg.sender); desiredLiquidity = uint256(-1); return pair; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Smelter.sol"; contract SmelterExploitMock { Smelter public immutable smelTer; constructor (address _smelTer) public{ smelTer = Smelter(_smelTer); } function convert(address token0, address token1) external { smelTer.convert(token0, token1); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../SmelterGoldVein.sol"; contract SmelterGoldVeinExploitMock { SmelterGoldVein public immutable smelTer; constructor(address _smelTer) public { smelTer = SmelterGoldVein(_smelTer); } function convert(IGoldVeinWithdrawFee goldveinPair) external { smelTer.convert(goldveinPair); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './interfaces/IUniswapV2Factory.sol'; import './UniswapV2Pair.sol'; contract UniswapV2Factory is IUniswapV2Factory { address public override feeTo; address public override feeToSetter; address public override migrator; mapping(address => mapping(address => address)) public override getPair; address[] public override allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function allPairsLength() external override view returns (uint) { return allPairs.length; } function pairCodeHash() external pure returns (bytes32) { return keccak256(type(UniswapV2Pair).creationCode); } function createPair(address tokenA, address tokenB) external override returns (address pair) { require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } UniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeTo = _feeTo; } function setMigrator(address _migrator) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); migrator = _migrator; } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeToSetter = _feeToSetter; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../uniswapv2/UniswapV2Factory.sol"; contract LuckySwapFactoryMock is UniswapV2Factory { constructor(address _feeToSetter) public UniswapV2Factory(_feeToSetter) {} } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./GoldNugget.sol"; interface IMigratorMiner { // Perform LP token migration from legacy UniswapV2 to LuckySwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // LuckySwap must mint EXACTLY the same amount of LuckySwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } contract GoldMiner is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of GOLNs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accGoldNuggetPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accGoldNuggetPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. GOLNs to distribute per block. uint256 lastRewardBlock; // Last block number that GOLNs distribution occurs. uint256 accGoldNuggetPerShare; // Accumulated GOLNs per share, times 1e12. See below. } // The GOLN TOKEN! GoldNugget public goldnugget; // Dev address. address public devaddr; // Block number when bonus GOLN period ends. uint256 public bonusEndBlock; // GOLN tokens created per block. uint256 public goldnuggetPerBlock; // Bonus muliplier for early goldnugget smelter. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorMiner public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when GOLN mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( GoldNugget _goldnugget, address _devaddr, uint256 _goldnuggetPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { goldnugget = _goldnugget; devaddr = _devaddr; goldnuggetPerBlock = _goldnuggetPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accGoldNuggetPerShare: 0 }) ); } // Update the given pool's GOLN allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorMiner _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending GOLNs on frontend. function pendingGoldNugget(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accGoldNuggetPerShare = pool.accGoldNuggetPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 goldnuggetReward = multiplier.mul(goldnuggetPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accGoldNuggetPerShare = accGoldNuggetPerShare.add( goldnuggetReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accGoldNuggetPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 goldnuggetReward = multiplier.mul(goldnuggetPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); goldnugget.mint(devaddr, goldnuggetReward.div(10)); goldnugget.mint(address(this), goldnuggetReward); pool.accGoldNuggetPerShare = pool.accGoldNuggetPerShare.add( goldnuggetReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to GoldMiner for GOLN allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accGoldNuggetPerShare).div(1e12).sub( user.rewardDebt ); safeGoldNuggetTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accGoldNuggetPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from GoldMiner. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accGoldNuggetPerShare).div(1e12).sub( user.rewardDebt ); safeGoldNuggetTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accGoldNuggetPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe goldnugget transfer function, just in case if rounding error causes pool to not have enough GOLNs. function safeGoldNuggetTransfer(address _to, uint256 _amount) internal { uint256 goldnuggetBal = goldnugget.balanceOf(address(this)); if (_amount > goldnuggetBal) { goldnugget.transfer(_to, goldnuggetBal); } else { goldnugget.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // GoldNugget with Governance. contract GoldNugget is ERC20("GoldNugget", "GOLN"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (GoldMiner). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GOLN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "GOLN::delegateBySig: invalid nonce"); require(now <= expiry, "GOLN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "GOLN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying GOLNs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "GOLN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20 { constructor( string memory name, string memory symbol, uint256 supply ) public ERC20(name, symbol) { _mint(msg.sender, supply); } }
Ingot helps your migrate your existing Uniswap LP tokens to LuckySwap LP ones
contract Ingot { using SafeERC20 for IERC20; IUniswapV2Router01 public oldRouter; IUniswapV2Router01 public router; constructor(IUniswapV2Router01 _oldRouter, IUniswapV2Router01 _router) public { oldRouter = _oldRouter; router = _router; } function migrateWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB)); pair.permit(msg.sender, address(this), liquidity, deadline, v, r, s); migrate(tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline); } function migrate( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) public { require(deadline >= block.timestamp, 'LuckySwap: EXPIRED'); (uint256 amountA, uint256 amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline ); (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB); if (amountA > pooledAmountA) { IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA); } if (amountB > pooledAmountB) { IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB); } } function migrate( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) public { require(deadline >= block.timestamp, 'LuckySwap: EXPIRED'); (uint256 amountA, uint256 amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline ); (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB); if (amountA > pooledAmountA) { IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA); } if (amountB > pooledAmountB) { IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB); } } function migrate( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) public { require(deadline >= block.timestamp, 'LuckySwap: EXPIRED'); (uint256 amountA, uint256 amountB) = removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, deadline ); (uint256 pooledAmountA, uint256 pooledAmountB) = addLiquidity(tokenA, tokenB, amountA, amountB); if (amountA > pooledAmountA) { IERC20(tokenA).safeTransfer(msg.sender, amountA - pooledAmountA); } if (amountB > pooledAmountB) { IERC20(tokenB).safeTransfer(msg.sender, amountB - pooledAmountB); } } function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Pair pair = IUniswapV2Pair(pairForOldRouter(tokenA, tokenB)); pair.transferFrom(msg.sender, address(pair), liquidity); (uint256 amount0, uint256 amount1) = pair.burn(address(this)); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'Ingot: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'Ingot: INSUFFICIENT_B_AMOUNT'); } function pairForOldRouter(address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = UniswapV2Library.sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', oldRouter.factory(), keccak256(abi.encodePacked(token0, token1)), )))); } function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint amountA, uint amountB) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired); address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB); IERC20(tokenA).safeTransfer(pair, amountA); IERC20(tokenB).safeTransfer(pair, amountB); IUniswapV2Pair(pair).mint(msg.sender); } function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } } else { function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired ) internal returns (uint256 amountA, uint256 amountB) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); if (factory.getPair(tokenA, tokenB) == address(0)) { factory.createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves(address(factory), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint256 amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { (amountA, amountB) = (amountADesired, amountBOptimal); uint256 amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } } else { }
175,764
[ 1, 382, 13212, 21814, 3433, 13187, 3433, 2062, 1351, 291, 91, 438, 511, 52, 2430, 358, 511, 9031, 93, 12521, 511, 52, 5945, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 657, 13212, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 1611, 1071, 1592, 8259, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 1611, 1071, 4633, 31, 203, 203, 203, 565, 3885, 12, 45, 984, 291, 91, 438, 58, 22, 8259, 1611, 389, 1673, 8259, 16, 467, 984, 291, 91, 438, 58, 22, 8259, 1611, 389, 10717, 13, 1071, 288, 203, 3639, 1592, 8259, 273, 389, 1673, 8259, 31, 203, 3639, 4633, 273, 389, 10717, 31, 203, 565, 289, 203, 203, 565, 445, 13187, 1190, 9123, 305, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 5034, 4501, 372, 24237, 16, 203, 3639, 2254, 5034, 3844, 2192, 267, 16, 203, 3639, 2254, 5034, 3844, 38, 2930, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 1071, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 4154, 3082, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 1290, 7617, 8259, 12, 2316, 37, 16, 1147, 38, 10019, 203, 3639, 3082, 18, 457, 1938, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 4501, 372, 24237, 16, 14096, 16, 331, 16, 436, 16, 272, 1769, 203, 203, 3639, 13187, 12, 2316, 37, 16, 1147, 38, 16, 4501, 372, 24237, 16, 3844, 2192, 267, 16, 3844, 38, 2930, 16, 2 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // &#39;B123&#39; token contract // // Deployed to : 0x61744c3f39D029A489849e71e79e8D8de67baFC6 // Symbol : B123 // Name : B123 Token // Total supply: 1000000 // Decimals : 18 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract B123Token is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function B123Token() public { symbol = "B123"; name = "B123 Token"; decimals = 18; _totalSupply = 1000000000000000000000000; balances[0x61744c3f39D029A489849e71e79e8D8de67baFC6] = _totalSupply; Transfer(address(0), 0x61744c3f39D029A489849e71e79e8D8de67baFC6, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to to account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don&#39;t accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract B123Token is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function B123Token() public { symbol = "B123"; name = "B123 Token"; decimals = 18; _totalSupply = 1000000000000000000000000; balances[0x61744c3f39D029A489849e71e79e8D8de67baFC6] = _totalSupply; Transfer(address(0), 0x61744c3f39D029A489849e71e79e8D8de67baFC6, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
15,345,314
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 12936, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 605, 12936, 1345, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 38, 12936, 14432, 203, 3639, 508, 273, 315, 38, 12936, 3155, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 9449, 31, 203, 3639, 324, 26488, 63, 20, 92, 26, 4033, 6334, 71, 23, 74, 5520, 40, 3103, 29, 37, 24, 6675, 5193, 29, 73, 11212, 73, 7235, 73, 28, 40, 28, 323, 9599, 12124, 4488, 26, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 92, 26, 4033, 6334, 71, 23, 74, 5520, 40, 3103, 29, 37, 24, 6675, 5193, 29, 73, 11212, 73, 7235, 73, 28, 40, 28, 323, 9599, 12124, 4488, 26, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 2 ]
./full_match/80001/0xba8178478C504d33527cF06f110D233992F43ca3/sources/contracts/Lending.sol
Check if the loan is overdue If the loan is overdue, terminate the user's NFT and stake Refund the amount paid in excess of the overdue loan Update the user's credit score Refund excess amount Send the principal amount back to the user
function payBackLoan() public payable nonReentrant { require(_loanBalances[msg.sender] > 0, "No active loan to repay"); require(msg.value > 0, "Must send a positive amount of ETH"); int256 loanStatus = checkLoanStatus(msg.sender); if (loanStatus == 0) { terminateLoan(msg.sender); if (msg.value > 0) { payable(msg.sender).transfer(msg.value); } return; } if (loanStatus > 0) { CreditScore.updateCreditScore(_userTokenId[msg.sender], 2); CreditScore.updateCreditScore(_userTokenId[msg.sender], -2); CreditScore.unlockNFT(_userTokenId[msg.sender]); } require(msg.value >= _loanBalances[msg.sender], "Insufficient repayment amount"); uint256 repaymentAmount = _loanBalances[msg.sender]; _loanBalances[msg.sender] = 0; _loanTimestamps[msg.sender] = 0; if (msg.value > repaymentAmount) { payable(msg.sender).transfer(msg.value - repaymentAmount); payable(msg.sender).transfer(msg.value - interestAmount); } emit LoanPaidBack(msg.sender, repaymentAmount); }
5,688,020
[ 1, 1564, 309, 326, 28183, 353, 1879, 24334, 971, 326, 28183, 353, 1879, 24334, 16, 10850, 326, 729, 1807, 423, 4464, 471, 384, 911, 3941, 1074, 326, 3844, 30591, 316, 23183, 434, 326, 1879, 24334, 28183, 2315, 326, 729, 1807, 12896, 4462, 3941, 1074, 23183, 3844, 2479, 326, 8897, 3844, 1473, 358, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 8843, 2711, 1504, 304, 1435, 1071, 8843, 429, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 24899, 383, 304, 38, 26488, 63, 3576, 18, 15330, 65, 405, 374, 16, 315, 2279, 2695, 28183, 358, 2071, 528, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 10136, 1366, 279, 6895, 3844, 434, 512, 2455, 8863, 203, 203, 3639, 509, 5034, 28183, 1482, 273, 866, 1504, 304, 1482, 12, 3576, 18, 15330, 1769, 203, 3639, 309, 261, 383, 304, 1482, 422, 374, 13, 288, 203, 5411, 10850, 1504, 304, 12, 3576, 18, 15330, 1769, 203, 5411, 309, 261, 3576, 18, 1132, 405, 374, 13, 288, 203, 7734, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 3576, 18, 1132, 1769, 203, 5411, 289, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 383, 304, 1482, 405, 374, 13, 288, 203, 5411, 30354, 7295, 18, 2725, 16520, 7295, 24899, 1355, 1345, 548, 63, 3576, 18, 15330, 6487, 576, 1769, 203, 5411, 30354, 7295, 18, 2725, 16520, 7295, 24899, 1355, 1345, 548, 63, 3576, 18, 15330, 6487, 300, 22, 1769, 203, 5411, 30354, 7295, 18, 26226, 50, 4464, 24899, 1355, 1345, 548, 63, 3576, 18, 15330, 19226, 203, 3639, 289, 203, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 389, 383, 304, 38, 26488, 63, 3576, 18, 15330, 6487, 315, 5048, 11339, 2071, 2955, 3844, 8863, 203, 203, 3639, 2254, 5034, 2071, 2955, 6275, 273, 389, 383, 304, 38, 26488, 63, 3576, 18, 15330, 15533, 203, 203, 3639, 389, 383, 2 ]
./partial_match/1313161554/0x1B991D143EEEb8830EA91ba0c11ceeA745fb9372/sources/MoxieSwapRouter02.sol
**** SWAP (supporting fee-on-transfer tokens) **** requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = MoxieSwapLibrary.sortTokens(input, output); IMoxieSwapPair pair = IMoxieSwapPair(MoxieSwapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = MoxieSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? MoxieSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); }
16,928,757
[ 1, 18746, 2203, 261, 13261, 310, 14036, 17, 265, 17, 13866, 2430, 13, 225, 4991, 326, 2172, 3844, 358, 1240, 1818, 2118, 3271, 358, 326, 1122, 3082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 22270, 6289, 310, 14667, 1398, 5912, 5157, 12, 2867, 8526, 3778, 589, 16, 1758, 389, 869, 13, 2713, 5024, 288, 203, 3639, 364, 261, 11890, 277, 31, 277, 411, 589, 18, 2469, 300, 404, 31, 277, 27245, 288, 203, 5411, 261, 2867, 810, 16, 1758, 876, 13, 273, 261, 803, 63, 77, 6487, 589, 63, 77, 397, 404, 19226, 203, 5411, 261, 2867, 1147, 20, 16, 13, 273, 490, 2409, 1385, 12521, 9313, 18, 3804, 5157, 12, 2630, 16, 876, 1769, 203, 5411, 6246, 2409, 1385, 12521, 4154, 3082, 273, 6246, 2409, 1385, 12521, 4154, 12, 49, 2409, 1385, 12521, 9313, 18, 6017, 1290, 12, 6848, 16, 810, 16, 876, 10019, 203, 5411, 2254, 3844, 1210, 31, 203, 5411, 2254, 3844, 1447, 31, 203, 5411, 261, 11890, 20501, 20, 16, 2254, 20501, 21, 16, 13, 273, 3082, 18, 588, 607, 264, 3324, 5621, 203, 5411, 261, 11890, 20501, 1210, 16, 2254, 20501, 1447, 13, 273, 810, 422, 1147, 20, 692, 261, 455, 6527, 20, 16, 20501, 21, 13, 294, 261, 455, 6527, 21, 16, 20501, 20, 1769, 203, 5411, 3844, 1210, 273, 467, 654, 39, 3462, 984, 291, 91, 438, 12, 2630, 2934, 12296, 951, 12, 2867, 12, 6017, 13, 2934, 1717, 12, 455, 6527, 1210, 1769, 203, 5411, 3844, 1447, 273, 490, 2409, 1385, 12521, 9313, 18, 588, 6275, 1182, 12, 8949, 1210, 16, 20501, 1210, 16, 20501, 1447, 1769, 203, 5411, 289, 203, 5411, 261, 11890, 3844, 20, 1182, 16, 2254, 3844, 21, 1182, 13, 273, 810, 422, 1147, 2 ]
./partial_match/56/0x1BdDac400bf9883011dff3C51C44a275065Bb8DD/sources/SyrupPresale.sol
@dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with GSN meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract Context { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
11,196,634
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 8770, 6835, 1772, 288, 203, 565, 289, 203, 203, 3639, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 8843, 429, 13, 288, 203, 5411, 327, 1234, 18, 15330, 31, 203, 3639, 289, 203, 203, 3639, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 13, 288, 203, 5411, 327, 1234, 18, 892, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. * @author Axiom Zen (https://www.axiomzen.co) * This code was taken from https://github.com/dapperlabs at * https://github.com/dapperlabs/cryptokitties-bounty and is NOT kleros code. */ pragma solidity ^0.4.18; import "./KittyBase.sol"; import "./ERC721.sol"; /// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyOwnership is KittyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public name = "CryptoKitties"; string public symbol = "CK"; // bool public implementsERC721 = true; // function implementsERC721() public pure returns (bool) { return true; } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Kitty. /// @param _claimant the address we are validating against. /// @param _tokenId kitten id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Kitty. /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return kittyIndexToApproved[_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 Kitties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { kittyIndexToApproved[_tokenId] = _approved; } /// @dev Transfers a kitty owned by this contract to the specified address. /// Used to rescue lost kitties. (There is no "proper" flow where this contract /// should be the owner of any Kitty. This function exists for us to reassign /// the ownership of Kitties that users may have accidentally sent to our address.) /// @param _kittyId - ID of kitty /// @param _recipient - Address to send the cat to function rescueLostKitty(uint256 _kittyId, address _recipient) public onlyCOO whenNotPaused { require(_owns(this, _kittyId)); _transfer(this, _recipient, _kittyId); } /// @notice Returns the number of Kitties owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Kitty to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Kitty to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // You can only send your own cat. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Kitty via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Kitty owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Kitty to be transfered. /// @param _to The address that should take ownership of the Kitty. Can be any address, /// including the caller. /// @param _tokenId The ID of the Kitty to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Kitties currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return kitties.length - 1; } /// @notice Returns the address currently assigned ownership of a given Kitty. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns the nth Kitty assigned to an address, with n specified by the /// _index argument. /// @param _owner The owner whose Kitties we are interested in. /// @param _index The zero-based index of the cat within the owner's list of cats. /// Must be less than balanceOf(_owner). /// @dev This method MUST NEVER be called by smart contract code. It will almost /// certainly blow past the block gas limit once there are a large number of /// Kitties in existence. Exists only to allow off-chain queries of ownership. /// Optional method for ERC-721. function tokensOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId) { uint256 count = 0; for (uint256 i = 1; i <= totalSupply(); i++) { if (kittyIndexToOwner[i] == _owner) { if (count == _index) { return i; } else { count++; } } } revert(); } }
@notice Returns the address currently assigned ownership of a given Kitty. @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = kittyIndexToOwner[_tokenId]; require(owner != address(0)); }
5,503,044
[ 1, 1356, 326, 1758, 4551, 6958, 23178, 434, 279, 864, 1475, 305, 4098, 18, 225, 10647, 364, 4232, 39, 17, 27, 5340, 29443, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3410, 951, 12, 11890, 5034, 389, 2316, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 3410, 13, 203, 565, 288, 203, 3639, 3410, 273, 31758, 4098, 1016, 774, 5541, 63, 67, 2316, 548, 15533, 203, 203, 3639, 2583, 12, 8443, 480, 1758, 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 ]
./partial_match/42/0x631a077C72Ec8bBBEC0af43Bbc60FB90Bb406883/sources/Master.sol
MarToken with Governance.
contract MARToken is ERC20("Marine.Cash", "MAR"), Ownable { address public governance; mapping (address => bool) public minters; constructor (address _presale_address) public { _mint(_presale_address, 10 ** 21); governance = msg.sender; } function mint(address _to, uint256 _amount) public { require(minters[msg.sender], "!minter"); _mint(_to, _amount); } function burn(uint256 _amount) public { require(minters[msg.sender], "!minter"); _burn(msg.sender, _amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = true; } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
3,363,959
[ 1, 49, 297, 1345, 598, 611, 1643, 82, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 985, 1345, 353, 4232, 39, 3462, 2932, 49, 297, 558, 18, 39, 961, 3113, 315, 19772, 6, 3631, 14223, 6914, 288, 203, 377, 203, 565, 1758, 1071, 314, 1643, 82, 1359, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 1131, 5432, 31, 203, 377, 203, 565, 3885, 261, 2867, 389, 12202, 5349, 67, 2867, 13, 1071, 288, 203, 3639, 389, 81, 474, 24899, 12202, 5349, 67, 2867, 16, 1728, 2826, 9035, 1769, 203, 3639, 314, 1643, 82, 1359, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 12, 1154, 5432, 63, 3576, 18, 15330, 6487, 17528, 1154, 387, 8863, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 18305, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 12, 1154, 5432, 63, 3576, 18, 15330, 6487, 17528, 1154, 387, 8863, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 26770, 1643, 82, 1359, 12, 2867, 389, 75, 1643, 82, 1359, 13, 1071, 288, 203, 1377, 2583, 12, 3576, 18, 15330, 422, 314, 1643, 82, 1359, 16, 17528, 75, 1643, 82, 1359, 8863, 203, 1377, 314, 1643, 82, 1359, 273, 389, 75, 1643, 82, 1359, 31, 203, 565, 289, 203, 21281, 565, 445, 527, 49, 2761, 12, 2867, 389, 1154, 387, 13, 1071, 288, 203, 1377, 2583, 2 ]
./partial_match/56/0x1A6861e2383C54A58ebF54d8217982dDfc83F1Fc/sources/LayerLock.sol
Allows Participants to withdraw funds when campaign fails
function withdrawFunds() public returns(uint){ require(failed() || doRefund,"campaign didn't fail"); require(participant[msg.sender] >0 ,"You didn't participate in the campaign"); uint withdrawAmount = participant[msg.sender].mul(uint(ILayerLockFactory(factory).fee())).div(1000); (msg.sender).transfer(withdrawAmount); payable(ILayerLockFactory(factory).toFee()).transfer(participant[msg.sender].sub(withdrawAmount)); participant[msg.sender] = 0; }
11,043,852
[ 1, 19132, 6393, 27620, 358, 598, 9446, 284, 19156, 1347, 8965, 6684, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 42, 19156, 1435, 1071, 1135, 12, 11890, 15329, 203, 3639, 2583, 12, 7307, 1435, 747, 741, 21537, 10837, 14608, 10242, 1404, 2321, 8863, 203, 3639, 2583, 12, 2680, 14265, 63, 3576, 18, 15330, 65, 405, 20, 269, 6, 6225, 10242, 1404, 30891, 340, 316, 326, 8965, 8863, 203, 3639, 2254, 598, 9446, 6275, 273, 14188, 63, 3576, 18, 15330, 8009, 16411, 12, 11890, 12, 2627, 1773, 2531, 1733, 12, 6848, 2934, 21386, 10756, 2934, 2892, 12, 18088, 1769, 203, 3639, 261, 3576, 18, 15330, 2934, 13866, 12, 1918, 9446, 6275, 1769, 203, 3639, 8843, 429, 12, 2627, 1773, 2531, 1733, 12, 6848, 2934, 869, 14667, 1435, 2934, 13866, 12, 2680, 14265, 63, 3576, 18, 15330, 8009, 1717, 12, 1918, 9446, 6275, 10019, 203, 3639, 14188, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 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 ]
./full_match/1/0xE10baE1903e48B4F544d319759e7f71Df9cf9A59/sources/contracts/Pool.sol
@notice Modifier that allows the method to be called only by the Service contract. @dev It is used to transfer control of the Registry and deployable user contracts for the final configuration of the company.
modifier onlyService() { require(msg.sender == address(service), ExceptionsLibrary.NOT_SERVICE); _; }
17,152,399
[ 1, 9829, 716, 5360, 326, 707, 358, 506, 2566, 1338, 635, 326, 1956, 6835, 18, 225, 2597, 353, 1399, 358, 7412, 3325, 434, 326, 5438, 471, 7286, 429, 729, 20092, 364, 326, 727, 1664, 434, 326, 9395, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 1179, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 3278, 3631, 12781, 9313, 18, 4400, 67, 12426, 1769, 203, 3639, 389, 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 ]
// solium-disable linebreak-style pragma solidity ^0.4.24; import "./Pedro_ERC20Token.sol"; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for Pedro_ERC20Token; // The token being sold address public tokenAddress; Pedro_ERC20Token pedro; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _tokenAddress Address of the token being sold */ constructor(uint256 _rate, address _wallet, address _tokenAddress) public { require(_rate > 0,"Rate should be greater than zero."); require(_wallet != address(0),"Can't send tokens to the 0x0 address."); require(_tokenAddress != address(0),"The 0x0 address has no ERC20 token contract."); owner = msg.sender; rate = _rate; wallet = _wallet; tokenAddress = _tokenAddress; pedro = Pedro_ERC20Token(tokenAddress); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens( address _beneficiary ) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); // _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); // _postValidatePurchase(_beneficiary, weiAmount); } // ---------------------------- // Internal crowdsale interface // ---------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(_beneficiary, _weiAmount); * require(weiRaised.add(_weiAmount) <= cap); * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal view onlyIfWhitelisted(_beneficiary) { require(_beneficiary != address(0),"Can't send tokens to the 0x0 address."); require(_weiAmount != 0,"Can't send tokens if you don't send any Ether."); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * param _beneficiary Address performing the token purchase * param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( //address _beneficiary, //uint256 _weiAmount ) internal pure { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { // Pedro_ERC20Token(token).safeTransfer(_beneficiary, _tokenAmount); pedro.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * param _beneficiary Address receiving the tokens * param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( // address _beneficiary, // uint256 _weiAmount ) internal pure { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } // ---------------------- // Whitelisting interface // ---------------------- 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]); } } // ------------------- // Ownership interface // ------------------- address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner,"Only owner can call this function."); _; } /** * @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),"You can't transfer ownership to the 0x0 address."); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } // --------------------------- // Role-based access interface // --------------------------- 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); _; } } /** * @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),"This address doesn't have this role."); } /** * @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]; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( Pedro_ERC20Token _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value),"Could not safely transfer from that address."); } function safeTransferFrom( Pedro_ERC20Token _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value),"Could not safely transfer from that address."); } function safeApprove( Pedro_ERC20Token _token, address _spender, uint256 _currentValue, uint256 _value ) internal { require(_token.approve(_spender, _currentValue, _value),"Could not safely approve, check current approved value."); } }
* @dev Throws if called by any account other than the owner./
modifier onlyOwner() { require(msg.sender == owner,"Only owner can call this function."); _; }
12,949,094
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3410, 10837, 3386, 3410, 848, 745, 333, 445, 1199, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract Z_ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract Z_ERC20 is Z_ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token implementation * @dev Basic version of StandardToken, with no allowances. */ contract Z_BasicToken is Z_ERC20Basic { mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token, implementing transfer by agents * * @dev Implementation of the basic standard token with allowances. * @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 Z_StandardToken is Z_ERC20, Z_BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another by agents within allowance limit * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @return true */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Transfer tokens from one address to by admin , without any allowance limit * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred * @return true */ function transferFromByAdmin(address _from, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); //require(_value <= 100000); balances[_from] -= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * @return true */ 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 Approve the passed address to spend the specified *additional* 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 _addedValue The additional amount of tokens to be spent. * @return true * 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) */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] + (_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the allownance quota by the specified amount of tokens * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to be decreased * @return true */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue - (_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and multiple admin addresses, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Z_Ownable { address public owner; mapping (address => bool) internal admin_accounts; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { // set msg.sender as owner owner = msg.sender; // set msg.sender as first administrator admin_accounts[msg.sender]= true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner ); _; } /** * @dev check if msg.sender is owner * @return true if msg.sender is owner */ function isOwner() internal view returns (bool) { return (msg.sender == owner ); } /** * @dev Throws if called by any account other than admins. */ modifier onlyAdmin() { require (admin_accounts[msg.sender]==true); _; } /** * @dev check if msg.sender is admin * @return true if msg.sender is admin */ function isAdmin() internal view returns (bool) { return (admin_accounts[msg.sender]==true); } } /** @title main contract for NOW token. we should deploy this contract. needs about 5,500,000 gas */ contract NOWToken is Z_StandardToken, Z_Ownable { string public constant name = "NOW Token"; string public constant symbol = "NOW"; uint8 public constant decimals = 18; // token traded in integer amounts, no period // total token supply: 3 billion NOW uint256 internal constant _totalTokenAmount = 3 * (10 ** 9) * (10 ** 18); uint256 internal constant WEI_PER_ETHER= 1000000000000000000; // 10^18 wei = 1 ether uint256 internal constant NUM_OF_SALE_STAGES= 5; // support upto five sale stages // enum type definition for sale status (0 ~ 13) enum Sale_Status { Initialized_STATUS, // 0 Stage0_Sale_Started_STATUS, // 1, stage0 Stage0_Sale_Stopped_STATUS, // 2, stage0 Stage1_Sale_Started_STATUS, // 3, stage1 Stage1_Sale_Stopped_STATUS, // 4, stage1 Stage2_Sale_Started_STATUS, // 5, stage2 Stage2_Sale_Stopped_STATUS, // 6, stage2 Stage3_Sale_Started_STATUS, // 7, stage3 Stage3_Sale_Stopped_STATUS, // 8, stage3 Stage4_Sale_Started_STATUS, // 9, stage4 Stage4_Sale_Stopped_STATUS, // 10, stage4 Public_Allowed_To_Trade_STATUS, // 11 Stage0_Allowed_To_Trade_STATUS, // 12 Closed_STATUS // 13 } // sale status variable: 0 ~ 13 (enum Sale_Status ) Sale_Status public sale_status= Sale_Status.Initialized_STATUS; // sale stage index : 0 ~ 4 ( 0:1~2, 1:3~4, 2:5~6, 3:7~8, 4:9~10) uint256 public sale_stage_index= 0; // 0 ~ 4 for stage0 ~ 4 // initiazlied time uint256 public when_initialized= 0; // timestamp when public trade begins except stage0 uint256 public when_public_allowed_to_trade_started= 0; // timestamp when *all* tokens trade begins including stage0 uint256 public when_stage0_allowed_to_trade_started= 0; // array of sale starting time's timestamp uint256 [NUM_OF_SALE_STAGES] public when_stageN_sale_started; // array of sale stopping time's timestamp uint256 [NUM_OF_SALE_STAGES] public when_stageN_sale_stopped; // sum of all sold tokens uint256 public sold_tokens_total= 0; // sum of ethers received during all token sale stages uint256 public raised_ethers_total= 0; // array of sold tokens per sale stage uint256[NUM_OF_SALE_STAGES] public sold_tokens_per_stage; // array of received ethers per sale stage uint256[NUM_OF_SALE_STAGES] public raised_ethers_per_stage; // target ether amount to gather in each sale stage, when fullfilled, the sale stage automatically forced to stop uint256[NUM_OF_SALE_STAGES] public target_ethers_per_stage= [ 1000 * WEI_PER_ETHER, // stage0 for staff 9882 * WEI_PER_ETHER, // stage1 for black sale 11454 * WEI_PER_ETHER, // stage2 for private sale 11200 * WEI_PER_ETHER, // stage3 for public sale 11667 * WEI_PER_ETHER // stage4 for crowd sale ]; // array of token sale price for each stage (wei per now) uint256[NUM_OF_SALE_STAGES] internal sale_price_per_stage_wei_per_now = [ uint256(1000000000000000000/ uint256(100000)),// stage0 for staff uint256(1000000000000000000/ uint256(38000)), // stage1 for black sale uint256(1000000000000000000/ uint256(23000)), // stage2 for private sale uint256(1000000000000000000/ uint256(17000)), // stage3 for public sale uint256(1000000000000000000/ uint256(10000)) // stage4 for crowd sale ]; // struct definition for token sale history struct history_token_sale_obj { address _buyer; uint256 _ether_value; // in wei uint256 _token_value; // in now token uint256 _when; } // struct definition for token transfer history struct history_token_transfer_obj { address _from; address _to; uint256 _token_value; // in now token uint256 _when; } // struct definition for token burning history struct history_token_burning_obj { address _from; uint256 _token_value_burned; // in now token uint256 _when; } // token sale history for stage 0 ~ 4 history_token_sale_obj[] internal history_token_sale_stage0; history_token_sale_obj[] internal history_token_sale_stage1; history_token_sale_obj[] internal history_token_sale_stage2; history_token_sale_obj[] internal history_token_sale_stage3; history_token_sale_obj[] internal history_token_sale_stage4; // token transfer history history_token_transfer_obj[] internal history_token_transfer; // token burning history history_token_burning_obj[] internal history_token_burning; // token sale amount for each account per stage 0 ~ 4 mapping (address => uint256) internal sale_amount_stage0_account; mapping (address => uint256) internal sale_amount_stage1_account; mapping (address => uint256) internal sale_amount_stage2_account; mapping (address => uint256) internal sale_amount_stage3_account; mapping (address => uint256) internal sale_amount_stage4_account; // array for list of holders and their receiving amounts mapping (address => uint256) internal holders_received_accumul; // array for list of holders accounts (including even inactive holders) address[] public holders; // array for list of sale holders accounts for each sale stage address[] public holders_stage0_sale; address[] public holders_stage1_sale; address[] public holders_stage2_sale; address[] public holders_stage3_sale; address[] public holders_stage4_sale; // array for list of trading holders which are not sale holders address[] public holders_trading; // array for list of burning holders accounts address[] public holders_burned; // array for list of frozen holders accounts address[] public holders_frozen; // burned tokens for each holders account mapping (address => uint256) public burned_amount; // sum of all burned tokens uint256 public totalBurned= 0; // total ether value withdrawed from this contract by contract owner uint256 public totalEtherWithdrawed= 0; // addess to timestamp mapping to mark the account freezing time ( 0 means later unfreezed ) mapping (address => uint256) internal account_frozen_time; // unused mapping (address => mapping (string => uint256)) internal traded_monthly; // cryptocurrency exchange office ether address, for monitorig purpose address[] public cryptocurrency_exchange_company_accounts; ///////////////////////////////////////////////////////////////////////// event AddNewAdministrator(address indexed _admin, uint256 indexed _when); event RemoveAdministrator(address indexed _admin, uint256 indexed _when); /** * @dev add new admin accounts * (run by admin, public function) * @param _newAdmin new admin address */ function z_admin_add_admin(address _newAdmin) public onlyOwner { require(_newAdmin != address(0)); admin_accounts[_newAdmin]=true; emit AddNewAdministrator(_newAdmin, block.timestamp); } /** * @dev remove old admin accounts * (run by admin, public function) * @param _oldAdmin old admin address */ function z_admin_remove_admin(address _oldAdmin) public onlyOwner { require(_oldAdmin != address(0)); require(admin_accounts[_oldAdmin]==true); admin_accounts[_oldAdmin]=false; emit RemoveAdministrator(_oldAdmin, block.timestamp); } event AddNewExchangeAccount(address indexed _exchange_account, uint256 indexed _when); /** * @dev add new exchange office accounts * (run by admin, public function) * @param _exchange_account new exchange address */ function z_admin_add_exchange(address _exchange_account) public onlyAdmin { require(_exchange_account != address(0)); cryptocurrency_exchange_company_accounts.push(_exchange_account); emit AddNewExchangeAccount(_exchange_account, block.timestamp); } event SaleTokenPriceSet(uint256 _stage_index, uint256 _wei_per_now_value, uint256 indexed _when); /** * @dev set new token sale price for current sale stage * (run buy admin, public function) * return _how_many_wei_per_now new token sale price (wei per now) */ function z_admin_set_sale_price(uint256 _how_many_wei_per_now) public onlyAdmin { if(_how_many_wei_per_now == 0) revert(); if(sale_stage_index >= 5) revert(); sale_price_per_stage_wei_per_now[sale_stage_index] = _how_many_wei_per_now; emit SaleTokenPriceSet(sale_stage_index, _how_many_wei_per_now, block.timestamp); } /** * @dev return current or last token sale price * (public view function) * return _sale_price get current token sale price (wei per now) * return _current_sale_stage_index get current sale stage index ( 0 ~ 4) */ function CurrentSalePrice() public view returns (uint256 _sale_price, uint256 _current_sale_stage_index) { if(sale_stage_index >= 5) revert(); _current_sale_stage_index= sale_stage_index; _sale_price= sale_price_per_stage_wei_per_now[sale_stage_index]; } event InitializedStage(uint256 indexed _when); event StartStage0TokenSale(uint256 indexed _when); event StartStage1TokenSale(uint256 indexed _when); event StartStage2TokenSale(uint256 indexed _when); event StartStage3TokenSale(uint256 indexed _when); event StartStage4TokenSale(uint256 indexed _when); /** * @dev start _new_sale_stage_index sale stage * (run by admin ) */ function start_StageN_Sale(uint256 _new_sale_stage_index) internal { if(sale_status==Sale_Status.Initialized_STATUS || sale_stage_index+1<= _new_sale_stage_index) sale_stage_index= _new_sale_stage_index; else revert(); sale_status= Sale_Status(1 + sale_stage_index * 2); // 0=>1, 1=>3, 2=>5, 3=>7, 4=>9 when_stageN_sale_started[sale_stage_index]= block.timestamp; if(sale_stage_index==0) emit StartStage0TokenSale(block.timestamp); if(sale_stage_index==1) emit StartStage1TokenSale(block.timestamp); if(sale_stage_index==2) emit StartStage2TokenSale(block.timestamp); if(sale_stage_index==3) emit StartStage3TokenSale(block.timestamp); if(sale_stage_index==4) emit StartStage4TokenSale(block.timestamp); } event StopStage0TokenSale(uint256 indexed _when); event StopStage1TokenSale(uint256 indexed _when); event StopStage2TokenSale(uint256 indexed _when); event StopStage3TokenSale(uint256 indexed _when); event StopStage4TokenSale(uint256 indexed _when); /** * @dev stop this [_old_sale_stage_index] sale stage * (run by admin ) */ function stop_StageN_Sale(uint256 _old_sale_stage_index) internal { if(sale_stage_index != _old_sale_stage_index) revert(); sale_status= Sale_Status(2 + sale_stage_index * 2); // 0=>2, 1=>4, 2=>6, 3=>8, 4=>10 when_stageN_sale_stopped[sale_stage_index]= block.timestamp; if(sale_stage_index==0) emit StopStage0TokenSale(block.timestamp); if(sale_stage_index==1) emit StopStage1TokenSale(block.timestamp); if(sale_stage_index==2) emit StopStage2TokenSale(block.timestamp); if(sale_stage_index==3) emit StopStage3TokenSale(block.timestamp); if(sale_stage_index==4) emit StopStage4TokenSale(block.timestamp); } event StartTradePublicSaleTokens(uint256 indexed _when); /** * @dev allow stage1~4 token trading * (run by admin ) */ function start_Public_Trade() internal onlyAdmin { // if current sale stage had not been stopped, first stop current active sale stage Sale_Status new_sale_status= Sale_Status(2 + sale_stage_index * 2); if(new_sale_status > sale_status) stop_StageN_Sale(sale_stage_index); sale_status= Sale_Status.Public_Allowed_To_Trade_STATUS; when_public_allowed_to_trade_started= block.timestamp; emit StartTradePublicSaleTokens(block.timestamp); } event StartTradeStage0SaleTokens(uint256 indexed _when); /** * @dev allow stage0 token trading * (run by admin ) */ function start_Stage0_Trade() internal onlyAdmin { if(sale_status!= Sale_Status.Public_Allowed_To_Trade_STATUS) revert(); // allowed 1 year later after stage1 tokens trading is enabled uint32 stage0_locked_year= 1; bool is_debug= false; // change to false if this contract source is release version if(is_debug==false && block.timestamp < stage0_locked_year*365*24*60*60 + when_public_allowed_to_trade_started ) revert(); if(is_debug==true && block.timestamp < stage0_locked_year*10*60 + when_public_allowed_to_trade_started ) revert(); sale_status= Sale_Status.Stage0_Allowed_To_Trade_STATUS; when_stage0_allowed_to_trade_started= block.timestamp; emit StartTradeStage0SaleTokens(block.timestamp); } event CreateTokenContract(uint256 indexed _when); /** * @dev token contract constructor(), initialized tokens supply and sale status variables * (run by owner when contract deploy) */ constructor() public { totalSupply = _totalTokenAmount; balances[msg.sender] = _totalTokenAmount; sale_status= Sale_Status.Initialized_STATUS; sale_stage_index= 0; when_initialized= block.timestamp; holders.push(msg.sender); holders_received_accumul[msg.sender] += _totalTokenAmount; emit Transfer(address(0x0), msg.sender, _totalTokenAmount); emit InitializedStage(block.timestamp); emit CreateTokenContract(block.timestamp); } /** * @dev check if specified token transfer request is valid * ( internal modifier function). * revert if transfer should be NOT allowed, otherwise do nothing * @param _from source account from whom tokens should be transferred * @param _to destination account to whom tokens should be transferred * @param _value number of tokens to be transferred */ modifier validTransaction( address _from, address _to, uint256 _value) { require(_to != address(0x0)); require(_to != _from); require(_value > 0); if(isAdmin()==false) { // if _from is frozen account, disallow this request if(account_frozen_time[_from] > 0) revert(); if(_value == 0 ) revert(); // if token trading is not enabled yet, disallow this request if(sale_status < Sale_Status.Public_Allowed_To_Trade_STATUS) revert(); // if stage0 token trading is not enabled yet, disallow this request if( sale_amount_stage0_account[_from] > 0 ) { if(sale_status < Sale_Status.Stage0_Allowed_To_Trade_STATUS) revert(); } else { } } _; } event TransferToken(address indexed _from_whom,address indexed _to_whom, uint _token_value, uint256 indexed _when); event TransferTokenFrom(address indexed _from_whom,address indexed _to_whom, address _agent, uint _token_value, uint256 indexed _when); event TransferTokenFromByAdmin(address indexed _from_whom,address indexed _to_whom, address _admin, uint _token_value, uint256 indexed _when); /** * @dev transfer specified amount of tokens from my account to _to account * (run by self, public function) * @param _to destination account to whom tokens should be transferred * @param _value number of tokens to be transferred * @return _success report if transfer was successful, on failure revert() */ function transfer(address _to, uint _value) public validTransaction(msg.sender, _to, _value) returns (bool _success) { _success= super.transfer(_to, _value); if(_success==false) revert(); emit TransferToken(msg.sender,_to,_value,block.timestamp); // check if new trading holder if(holders_received_accumul[_to]==0x0) { // new holder comes holders.push(_to); holders_trading.push(_to); emit NewHolderTrading(_to, block.timestamp); } holders_received_accumul[_to] += _value; // leave a transfer history entry history_token_transfer.push( history_token_transfer_obj( { _from: msg.sender, _to: _to, _token_value: _value, _when: block.timestamp } ) ); } /** * @dev transfer specified amount of tokens from _from account to _to account * (run by agent, public function) * @param _from client account who approved transaction performed by this sender as agent * @param _to destination account to whom tokens should be transferred * @param _value number of tokens to be transferred * @return _success report if transfer was successful, on failure revert() */ function transferFrom(address _from, address _to, uint _value) public validTransaction(_from, _to, _value) returns (bool _success) { if(isAdmin()==true) { // admins can transfer tokens of **ANY** accounts emit TransferTokenFromByAdmin(_from,_to,msg.sender,_value,block.timestamp); _success= super.transferFromByAdmin(_from,_to, _value); } else { // approved agents can transfer tokens of their clients (clients shoukd 'approve()' agents first) emit TransferTokenFrom(_from,_to,msg.sender,_value,block.timestamp); _success= super.transferFrom(_from, _to, _value); } if(_success==false) revert(); // check if new trading holder if(holders_received_accumul[_to]==0x0) { // new holder comes holders.push(_to); holders_trading.push(_to); emit NewHolderTrading(_to, block.timestamp); } holders_received_accumul[_to] += _value; // leave a transfer history entry history_token_transfer.push( history_token_transfer_obj( { _from: _from, _to: _to, _token_value: _value, _when: block.timestamp } ) ); } event IssueTokenSale(address indexed _buyer, uint _ether_value, uint _token_value, uint _exchange_rate_now_per_wei, uint256 indexed _when); /** * @dev fallback function for incoming ether, receive ethers and give tokens back */ function () public payable { buy(); } event NewHolderTrading(address indexed _new_comer, uint256 indexed _when); event NewHolderSale(address indexed _new_comer, uint256 indexed _when); /** * @dev buy now tokens by sending some ethers to this contract address * (payable public function ) */ function buy() public payable { if(sale_status < Sale_Status.Stage0_Sale_Started_STATUS) revert(); if(sale_status > Sale_Status.Stage4_Sale_Stopped_STATUS) revert(); if((uint256(sale_status)%2)!=1) revert(); // not in started sale status if(isAdmin()==true) revert(); // admins are not allowed to buy tokens uint256 tokens; uint256 wei_per_now= sale_price_per_stage_wei_per_now[sale_stage_index]; // if sent ether value is less than exch_rate, revert if (msg.value < wei_per_now) revert(); // calculate num of bought tokens based on sent ether value (in wei) tokens = uint256( msg.value / wei_per_now ); if (tokens + sold_tokens_total > totalSupply) revert(); // update token sale statistics per stage if(sale_stage_index==0) sale_amount_stage0_account[msg.sender] += tokens; else if(sale_stage_index==1) sale_amount_stage1_account[msg.sender] += tokens; else if(sale_stage_index==2) sale_amount_stage2_account[msg.sender] += tokens; else if(sale_stage_index==3) sale_amount_stage3_account[msg.sender] += tokens; else if(sale_stage_index==4) sale_amount_stage4_account[msg.sender] += tokens; sold_tokens_per_stage[sale_stage_index] += tokens; sold_tokens_total += tokens; // update ether statistics raised_ethers_per_stage[sale_stage_index] += msg.value; raised_ethers_total += msg.value; super.transferFromByAdmin(owner, msg.sender, tokens); // check if this holder is new if(holders_received_accumul[msg.sender]==0x0) { // new holder comes holders.push(msg.sender); if(sale_stage_index==0) holders_stage0_sale.push(msg.sender); else if(sale_stage_index==1) holders_stage1_sale.push(msg.sender); else if(sale_stage_index==2) holders_stage2_sale.push(msg.sender); else if(sale_stage_index==3) holders_stage3_sale.push(msg.sender); else if(sale_stage_index==4) holders_stage4_sale.push(msg.sender); emit NewHolderSale(msg.sender, block.timestamp); } holders_received_accumul[msg.sender] += tokens; // leave a token sale history entry history_token_sale_obj memory history = history_token_sale_obj( { _buyer: msg.sender, _ether_value: msg.value, _token_value: tokens, _when: block.timestamp } ); if(sale_stage_index==0) history_token_sale_stage0.push( history ); else if(sale_stage_index==1) history_token_sale_stage1.push( history ); else if(sale_stage_index==2) history_token_sale_stage2.push( history ); else if(sale_stage_index==3) history_token_sale_stage3.push( history ); else if(sale_stage_index==4) history_token_sale_stage4.push( history ); emit IssueTokenSale(msg.sender, msg.value, tokens, wei_per_now, block.timestamp); // if target ether is reached, stop this sale stage if( target_ethers_per_stage[sale_stage_index] <= raised_ethers_per_stage[sale_stage_index]) stop_StageN_Sale(sale_stage_index); } event FreezeAccount(address indexed _account_to_freeze, uint256 indexed _when); event UnfreezeAccount(address indexed _account_to_unfreeze, uint256 indexed _when); /** * @dev freeze a holder account, prohibit further token transfer * (run by ADMIN, public function) * @param _account_to_freeze account to freeze */ function z_admin_freeze(address _account_to_freeze) public onlyAdmin { account_frozen_time[_account_to_freeze]= block.timestamp; holders_frozen.push(_account_to_freeze); emit FreezeAccount(_account_to_freeze,block.timestamp); } /** * @dev unfreeze a holder account * (run by ADMIN, public function) * @param _account_to_unfreeze account to unfreeze (previously frozen) */ function z_admin_unfreeze(address _account_to_unfreeze) public onlyAdmin { account_frozen_time[_account_to_unfreeze]= 0; // reset time to zero emit UnfreezeAccount(_account_to_unfreeze,block.timestamp); } event CloseTokenContract(uint256 indexed _when); /** * @dev close this contract after burning all tokens * (run by ADMIN, public function ) */ function closeContract() onlyAdmin internal { if(sale_status < Sale_Status.Stage0_Allowed_To_Trade_STATUS) revert(); if(totalSupply > 0) revert(); address ScAddress = this; emit CloseTokenContract(block.timestamp); emit WithdrawEther(owner,ScAddress.balance,block.timestamp); selfdestruct(owner); } /** * @dev retrieve contract's ether balance info * (public view function) * @return _current_ether_balane current contract ethereum balance ( in wei unit) * @return _ethers_withdrawn withdrawen ethers in wei * @return _ethers_raised_total total ethers gathered from token sale */ function ContractEtherBalance() public view returns ( uint256 _current_ether_balance, uint256 _ethers_withdrawn, uint256 _ethers_raised_total ) { _current_ether_balance= address(this).balance; _ethers_withdrawn= totalEtherWithdrawed; _ethers_raised_total= raised_ethers_total; } event WithdrawEther(address indexed _addr, uint256 _value, uint256 indexed _when); /** * @dev transfer this contract ether balance to owner's account * ( public function ) * @param _withdraw_wei_value amount to widthdraw ( in wei unit) */ function z_admin_withdraw_ether(uint256 _withdraw_wei_value) onlyAdmin public { address ScAddress = this; if(_withdraw_wei_value > ScAddress.balance) revert(); //if(owner.call.value(_withdraw_wei_value).gas(5000)()==false) revert(); if(owner.send(_withdraw_wei_value)==false) revert(); totalEtherWithdrawed += _withdraw_wei_value; emit WithdrawEther(owner,_withdraw_wei_value,block.timestamp); } /** * @dev return list of active holders accounts and their balances * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest accounts items to display ( 0 means 1 ) * @return _num_of_active_holders number of latest holders accounts * @return _active_holders array of active( balance > 0) holders * @return _token_balances array of token balances */ function list_active_holders_and_balances(uint _max_num_of_items_to_display) public view returns (uint _num_of_active_holders,address[] _active_holders,uint[] _token_balances){ uint len = holders.length; _num_of_active_holders = 0; if(_max_num_of_items_to_display==0) _max_num_of_items_to_display=1; for (uint i = len-1 ; i >= 0 ; i--) { if( balances[ holders[i] ] != 0x0) _num_of_active_holders++; if(_max_num_of_items_to_display == _num_of_active_holders) break; } _active_holders = new address[](_num_of_active_holders); _token_balances = new uint[](_num_of_active_holders); uint num=0; for (uint j = len-1 ; j >= 0 && _num_of_active_holders > num ; j--) { address addr = holders[j]; if( balances[ addr ] == 0x0) continue; // assure balance > 0 _active_holders[num] = addr; _token_balances[num] = balances[addr]; num++; } } /** * @dev return list of recent stage0 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage0_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage0.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage0[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage1 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage1_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage1.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage1[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage2 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage2_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage2.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage2[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage3 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage3_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage3.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage3[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of recent stage4 token sale history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest token sale history items * @return _sale_holders array of holders * @return _ethers array of ethers paid * @return _tokens array of tokens bought * @return _whens array of sale times */ function list_history_of_stage4_sale(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _sale_holders,uint[] _ethers,uint[] _tokens,uint[] _whens){ uint len = history_token_sale_stage4.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _sale_holders = new address[](n); _ethers = new uint[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_sale_obj storage obj= history_token_sale_stage4[j]; _sale_holders[_num]= obj._buyer; _ethers[_num]= obj._ether_value; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of latest #N transfer history * ( public view function ) * @param _max_num_of_items_to_display Max Number of latest history items to display ( 0 means 1 ) * @return _num number of latest transfer history items * @return _senders array of senders * @return _receivers array of receivers * @return _tokens array of tokens transferred * @return _whens array of transfer times */ function list_history_of_token_transfer(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _senders,address[] _receivers,uint[] _tokens,uint[] _whens){ uint len = history_token_transfer.length; uint n= len; if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; if(_max_num_of_items_to_display < n) n= _max_num_of_items_to_display; _senders = new address[](n); _receivers = new address[](n); _tokens = new uint[](n); _whens = new uint[](n); _num=0; for (uint j = len-1 ; j >= 0 && n > _num ; j--) { history_token_transfer_obj storage obj= history_token_transfer[j]; _senders[_num]= obj._from; _receivers[_num]= obj._to; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return list of latest address-filtered #N transfer history * ( public view function ) * @param _addr address as filter for transfer history (default 0x0) * @return _num number of latest transfer history items * @return _senders array of senders * @return _receivers array of receivers * @return _tokens array of tokens transferred * @return _whens array of transfer times */ function list_history_of_token_transfer_filtered_by_addr(address _addr) public view returns (uint _num,address[] _senders,address[] _receivers,uint[] _tokens,uint[] _whens){ uint len = history_token_transfer.length; uint _max_num_of_items_to_display= 0; history_token_transfer_obj storage obj= history_token_transfer[0]; uint j; for (j = len-1 ; j >= 0 ; j--) { obj= history_token_transfer[j]; if(obj._from== _addr || obj._to== _addr) _max_num_of_items_to_display++; } if(_max_num_of_items_to_display == 0) _max_num_of_items_to_display= 1; _senders = new address[](_max_num_of_items_to_display); _receivers = new address[](_max_num_of_items_to_display); _tokens = new uint[](_max_num_of_items_to_display); _whens = new uint[](_max_num_of_items_to_display); _num=0; for (j = len-1 ; j >= 0 && _max_num_of_items_to_display > _num ; j--) { obj= history_token_transfer[j]; if(obj._from!= _addr && obj._to!= _addr) continue; _senders[_num]= obj._from; _receivers[_num]= obj._to; _tokens[_num]= obj._token_value; _whens[_num]= obj._when; _num++; } } /** * @dev return frozen accounts and their balances * ( public view function ) * @param _max_num_of_items_to_display Max Number of items to display ( 0 means 1 ) * @return _num number of currently frozen accounts * @return _frozen_holders array of frozen accounts * @return _whens array of frozen times */ function list_frozen_accounts(uint _max_num_of_items_to_display) public view returns (uint _num,address[] _frozen_holders,uint[] _whens){ uint len = holders_frozen.length; uint num_of_frozen_holders = 0; if(_max_num_of_items_to_display==0) _max_num_of_items_to_display=1; for (uint i = len-1 ; i >= 0 ; i--) { // assure currently in frozen state if( account_frozen_time[ holders_frozen[i] ] > 0x0) num_of_frozen_holders++; if(_max_num_of_items_to_display == num_of_frozen_holders) break; } _frozen_holders = new address[](num_of_frozen_holders); _whens = new uint[](num_of_frozen_holders); _num=0; for (uint j = len-1 ; j >= 0 && num_of_frozen_holders > _num ; j--) { address addr= holders_frozen[j]; uint256 when= account_frozen_time[ addr ]; if( when == 0x0) continue; // assure if frozen true _frozen_holders[_num]= addr; _whens[_num]= when; _num++; } } /** * @dev Token sale sumilation for current sale stage * ( public view function ) * @param _ether_or_wei_value input ethereum value (in wei or ether unit) * @return _num_of_tokens number of tokens that can be bought with the input value * @return _exch_rate current sale stage exchange rate (wei per now) * @return _current_sale_stage_index current sale stage index */ function simulate_token_sale(uint _ether_or_wei_value) public view returns (uint256 _num_of_tokens, uint256 _exch_rate, uint256 _current_sale_stage_index) { if(sale_stage_index >=5 ) return (0,0,0); _exch_rate= sale_price_per_stage_wei_per_now[sale_stage_index]; _current_sale_stage_index= sale_stage_index; // determine whether the input value is in ether unit or in wei unit if(_ether_or_wei_value>=1000000) _num_of_tokens= uint256( _ether_or_wei_value / _exch_rate ); // guess it is in wei else _num_of_tokens= uint256( _ether_or_wei_value * WEI_PER_ETHER / _exch_rate ); // guess it is in ether } /** * @dev Admin menu: Token Sale Status management * (run by admin, public function) * @param _next_status next status index (1 ~ 13). refer to enum Sale_Status */ function z_admin_next_status(Sale_Status _next_status) onlyAdmin public { if(_next_status== Sale_Status.Stage0_Sale_Started_STATUS) { start_StageN_Sale(0); return;} // 1 if(_next_status== Sale_Status.Stage0_Sale_Stopped_STATUS) { stop_StageN_Sale(0); return;} // 2 if(_next_status== Sale_Status.Stage1_Sale_Started_STATUS) { start_StageN_Sale(1); return;} // 3 if(_next_status== Sale_Status.Stage1_Sale_Stopped_STATUS) { stop_StageN_Sale(1); return;} // 4 if(_next_status== Sale_Status.Stage2_Sale_Started_STATUS) { start_StageN_Sale(2); return;} // 5 if(_next_status== Sale_Status.Stage2_Sale_Stopped_STATUS) { stop_StageN_Sale(2); return;} // 6 if(_next_status== Sale_Status.Stage3_Sale_Started_STATUS) { start_StageN_Sale(3); return;} // 7 if(_next_status== Sale_Status.Stage3_Sale_Stopped_STATUS) { stop_StageN_Sale(3); return;} // 8 if(_next_status== Sale_Status.Stage4_Sale_Started_STATUS) { start_StageN_Sale(4); return;} // 9 if(_next_status== Sale_Status.Stage4_Sale_Stopped_STATUS) { stop_StageN_Sale(4); return;} // 10 if(_next_status== Sale_Status.Public_Allowed_To_Trade_STATUS) { start_Public_Trade(); return;} //11 if(_next_status== Sale_Status.Stage0_Allowed_To_Trade_STATUS) { start_Stage0_Trade(); return;} //12 if(_next_status== Sale_Status.Closed_STATUS) { closeContract(); return;} //13 revert(); } }
* @title Standard ERC20 token, implementing transfer by agents @dev Implementation of the basic standard token with allowances./
contract Z_StandardToken is Z_ERC20, Z_BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function transferFromByAdmin(address _from, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); balances[_from] -= _value; balances[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] + (_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue - (_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue - (_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } else { }
13,028,442
[ 1, 8336, 4232, 39, 3462, 1147, 16, 19981, 225, 7412, 635, 16423, 225, 25379, 434, 326, 5337, 4529, 1147, 598, 1699, 6872, 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, 16351, 2285, 67, 8336, 1345, 353, 2285, 67, 654, 39, 3462, 16, 2285, 67, 8252, 1345, 288, 203, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2713, 2935, 31, 203, 7010, 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, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 2080, 19226, 203, 565, 2583, 24899, 1132, 1648, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 19226, 203, 203, 565, 324, 26488, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 565, 324, 26488, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 565, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 1265, 858, 4446, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 2713, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 2080, 19226, 203, 203, 565, 324, 26488, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 565, 324, 26488, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 203, 565, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; // Part: IStrategy interface IStrategy { function harvest(address caller) external returns (uint256 harvested); function totalUnderlying() external view returns (uint256 total); function stake(uint256 _amount) external; function withdraw(uint256 _amount) external; function setApprovals() external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/IERC20Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/Ownable /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: OpenZeppelin/[email protected]/ERC20 /** * @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, 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: GenericVault.sol contract GenericUnionVault is ERC20, Ownable { using SafeERC20 for IERC20; uint256 public withdrawalPenalty = 100; uint256 public constant MAX_WITHDRAWAL_PENALTY = 150; uint256 public platformFee = 500; uint256 public constant MAX_PLATFORM_FEE = 2000; uint256 public callIncentive = 500; uint256 public constant MAX_CALL_INCENTIVE = 500; uint256 public constant FEE_DENOMINATOR = 10000; address public immutable underlying; address public strategy; address public platform; event Harvest(address indexed _caller, uint256 _value); event Deposit(address indexed _from, address indexed _to, uint256 _value); event Withdraw(address indexed _from, address indexed _to, uint256 _value); event WithdrawalPenaltyUpdated(uint256 _penalty); event CallerIncentiveUpdated(uint256 _incentive); event PlatformFeeUpdated(uint256 _fee); event PlatformUpdated(address indexed _platform); event StrategySet(address indexed _strategy); constructor(address _token) ERC20( string(abi.encodePacked("Unionized ", ERC20(_token).name())), string(abi.encodePacked("u", ERC20(_token).symbol())) ) { underlying = _token; } /// @notice Updates the withdrawal penalty /// @param _penalty - the amount of the new penalty (in BIPS) function setWithdrawalPenalty(uint256 _penalty) external onlyOwner { require(_penalty <= MAX_WITHDRAWAL_PENALTY); withdrawalPenalty = _penalty; emit WithdrawalPenaltyUpdated(_penalty); } /// @notice Updates the caller incentive for harvests /// @param _incentive - the amount of the new incentive (in BIPS) function setCallIncentive(uint256 _incentive) external onlyOwner { require(_incentive <= MAX_CALL_INCENTIVE); callIncentive = _incentive; emit CallerIncentiveUpdated(_incentive); } /// @notice Updates the part of yield redirected to the platform /// @param _fee - the amount of the new platform fee (in BIPS) function setPlatformFee(uint256 _fee) external onlyOwner { require(_fee <= MAX_PLATFORM_FEE); platformFee = _fee; emit PlatformFeeUpdated(_fee); } /// @notice Updates the address to which platform fees are paid out /// @param _platform - the new platform wallet address function setPlatform(address _platform) external onlyOwner notToZeroAddress(_platform) { platform = _platform; emit PlatformUpdated(_platform); } /// @notice Set the address of the strategy contract /// @dev Can only be set once /// @param _strategy - address of the strategy contract function setStrategy(address _strategy) external onlyOwner notToZeroAddress(_strategy) { require(strategy == address(0), "Strategy already set"); strategy = _strategy; emit StrategySet(_strategy); } /// @notice Query the amount currently staked /// @return total - the total amount of tokens staked function totalUnderlying() public view returns (uint256 total) { return IStrategy(strategy).totalUnderlying(); } /// @notice Returns the amount of underlying a user can claim /// @param user - address whose claimable amount to query /// @return amount - claimable amount /// @dev Does not account for penalties and fees function balanceOfUnderlying(address user) external view returns (uint256 amount) { require(totalSupply() > 0, "No users"); return ((balanceOf(user) * totalUnderlying()) / totalSupply()); } /// @notice Deposit user funds in the autocompounder and mints tokens /// representing user's share of the pool in exchange /// @param _to - the address that will receive the shares /// @param _amount - the amount of underlying to deposit /// @return _shares - the amount of shares issued function deposit(address _to, uint256 _amount) public notToZeroAddress(_to) returns (uint256 _shares) { require(_amount > 0, "Deposit too small"); uint256 _before = totalUnderlying(); IERC20(underlying).safeTransferFrom(msg.sender, strategy, _amount); IStrategy(strategy).stake(_amount); // Issues shares in proportion of deposit to pool amount uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount * totalSupply()) / _before; } _mint(_to, shares); emit Deposit(msg.sender, _to, _amount); return shares; } /// @notice Deposit all of user's underlying balance /// @param _to - the address that will receive the shares /// @return _shares - the amount of shares issued function depositAll(address _to) external returns (uint256 _shares) { return deposit(_to, IERC20(underlying).balanceOf(msg.sender)); } /// @notice Unstake underlying in proportion to the amount of shares sent /// @param _shares - the number of shares sent /// @return _withdrawable - the withdrawable underlying amount function _withdraw(uint256 _shares) internal returns (uint256 _withdrawable) { require(totalSupply() > 0); // Computes the amount withdrawable based on the number of shares sent uint256 amount = (_shares * totalUnderlying()) / totalSupply(); // Burn the shares before retrieving tokens _burn(msg.sender, _shares); // If user is last to withdraw, harvest before exit if (totalSupply() == 0) { harvest(); IStrategy(strategy).withdraw(totalUnderlying()); _withdrawable = IERC20(underlying).balanceOf(address(this)); } // Otherwise compute share and unstake else { _withdrawable = amount; // Substract a small withdrawal fee to prevent users "timing" // the harvests. The fee stays staked and is therefore // redistributed to all remaining participants. uint256 _penalty = (_withdrawable * withdrawalPenalty) / FEE_DENOMINATOR; _withdrawable = _withdrawable - _penalty; IStrategy(strategy).withdraw(_withdrawable); } return _withdrawable; } /// @notice Unstake underlying token in proportion to the amount of shares sent /// @param _to - address to send underlying to /// @param _shares - the number of shares sent /// @return withdrawn - the amount of underlying returned to the user function withdraw(address _to, uint256 _shares) public notToZeroAddress(_to) returns (uint256 withdrawn) { // Withdraw requested amount of underlying uint256 _withdrawable = _withdraw(_shares); // And sends back underlying to user IERC20(underlying).safeTransfer(_to, _withdrawable); emit Withdraw(msg.sender, _to, _withdrawable); return _withdrawable; } /// @notice Withdraw all of a users' position as underlying /// @param _to - address to send underlying to /// @return withdrawn - the amount of underlying returned to the user function withdrawAll(address _to) external notToZeroAddress(_to) returns (uint256 withdrawn) { return withdraw(_to, balanceOf(msg.sender)); } /// @notice Claim rewards and swaps them to FXS for restaking /// @dev Can be called by anyone against an incentive in FXS /// @dev Harvest logic in the strategy contract function harvest() public { uint256 _harvested = IStrategy(strategy).harvest(msg.sender); emit Harvest(msg.sender, _harvested); } modifier notToZeroAddress(address _to) { require(_to != address(0), "Invalid address!"); _; } }
@notice Claim rewards and swaps them to FXS for restaking @dev Can be called by anyone against an incentive in FXS @dev Harvest logic in the strategy contract
function harvest() public { uint256 _harvested = IStrategy(strategy).harvest(msg.sender); emit Harvest(msg.sender, _harvested); }
1,505,365
[ 1, 9762, 283, 6397, 471, 1352, 6679, 2182, 358, 478, 60, 55, 364, 3127, 6159, 225, 4480, 506, 2566, 635, 1281, 476, 5314, 392, 316, 2998, 688, 316, 478, 60, 55, 225, 670, 297, 26923, 4058, 316, 326, 6252, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 1435, 1071, 288, 203, 3639, 2254, 5034, 389, 30250, 90, 3149, 273, 467, 4525, 12, 14914, 2934, 30250, 26923, 12, 3576, 18, 15330, 1769, 203, 3639, 3626, 670, 297, 26923, 12, 3576, 18, 15330, 16, 389, 30250, 90, 3149, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xEb401fab7F573Ea207c6980E4341D5bBdB0D9Eb8/sources/contracts/AnbotoExecV2.sol
Check if enough output tokens were received by the swap.
checkOutputAmount(_order, sliceInputAmount, swapOutputBalanceCorrected);
4,987,404
[ 1, 1564, 309, 7304, 876, 2430, 4591, 5079, 635, 326, 7720, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 866, 1447, 6275, 24899, 1019, 16, 2788, 1210, 6275, 16, 7720, 1447, 13937, 16147, 329, 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 ]
pragma solidity 0.6.12; // SPDX-License-Identifier: MIT /* * @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 /** * @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 /** * @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 /** * @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 /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT /** * @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 /** * @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 /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT interface IPancakeswapFarm { function poolLength() external view returns (uint256); function userInfo() external view returns (uint256); // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); // View function to see pending CAKEs on frontend. function pendingCake(uint256 _pid, address _user) external view returns (uint256); function pendingMDO(uint256 _pid, address _user) external view returns (uint256); function pendingShare(uint256 _pid, address _user) external view returns (uint256); function pendingBDO(uint256 _pid, address _user) external view returns (uint256); function pendingRewards(uint256 _pid, address _user) external view returns (uint256); function pendingReward(uint256 _pid, address _user) external view returns (uint256); function pendingBELT(uint256 _pid, address _user) external view returns (uint256); function pendingBusd(uint256 _pid, address _user) external view returns (uint256); // Deposit LP tokens to MasterChef for CAKE allocation. function deposit(uint256 _pid, uint256 _amount) external; // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external; // Stake CAKE tokens to MasterChef function enterStaking(uint256 _amount) external; // Withdraw CAKE tokens from STAKING. function leaveStaking(uint256 _amount) external; // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external; } // SPDX-License-Identifier: MIT interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // SPDX-License-Identifier: MIT interface ITreasury { function notifyExternalReward(uint256 _amount) external; } // SPDX-License-Identifier: MIT contract BvaultsStrategy is Ownable, ReentrancyGuard, Pausable { // Maximises yields in pancakeswap using SafeMath for uint256; using SafeERC20 for IERC20; bool public isAutoComp; // this vault is purely for staking. eg. WBNB-BDO staking vault. address public farmContractAddress; // address of farm, eg, PCS, Thugs etc. uint256 public pid; // pid of pool in farmContractAddress address public wantAddress; address public token0Address; address public token1Address; address public earnedAddress; address public uniRouterAddress = address(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F); // PancakeSwap: Router mapping(address => mapping(address => address[])) public paths; address public constant wbnbAddress = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); address public constant busdAddress = address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56); address public operator; address public strategist; address public timelock = address(0x92a082Ad5A942140bCC791081F775900d0A514D9); // 24h timelock bool public notPublic = false; // allow public to call earn() function uint256 public lastEarnBlock = 0; uint256 public wantLockedTotal = 0; uint256 public sharesTotal = 0; uint256 public controllerFee = 0; uint256 public constant controllerFeeMax = 10000; // 100 = 1% uint256 public constant controllerFeeUL = 300; uint256 public constant buyBackRateMax = 10000; // 100 = 1% uint256 public constant buyBackRateUL = 800; // 8% uint256 public buyBackRate1 = 300; // 3% address public buyBackToken1 = address(0x81859801b01764D4f0Fa5E64729f5a6C3b91435b); // BFI address public buyBackAddress1 = address(0x000000000000000000000000000000000000dEaD); // to burn uint256 public buyBackRate2 = 200; // 2% address public buyBackToken2 = address(0x190b589cf9Fb8DDEabBFeae36a813FFb2A702454); // BDO address public buyBackAddress2 = address(0x000000000000000000000000000000000000dEaD); // to burn uint256 public entranceFeeFactor = 10000; // 0% entrance fee (goes to pool + prevents front-running) uint256 public constant entranceFeeFactorMax = 10000; // 100 = 1% uint256 public constant entranceFeeFactorLL = 9950; // 0.5% is the max entrance fee settable. LL = lowerlimit event Deposit(uint256 amount); event Withdraw(uint256 amount); event Farm(uint256 amount); event Compound(address token0Address, uint256 token0Amt, address token1Address, uint256 token1Amt); event Earned(address earnedAddress, uint256 earnedAmt); event BuyBack(address earnedAddress, address buyBackToken, uint earnedAmt, uint256 buyBackAmt, address receiver); event DistributeFee(address earnedAddress, uint256 fee, address receiver); event ConvertDustToEarned(address tokenAddress, address earnedAddress, uint256 tokenAmt); event InCaseTokensGetStuck(address tokenAddress, uint256 tokenAmt, address receiver); event ExecuteTransaction(address indexed target, uint256 value, string signature, bytes data); // _controller: BvaultsBank // _buyBackToken1Info[]: buyBackToken1, buyBackAddress1, buyBackToken1MidRouteAddress // _buyBackToken2Info[]: buyBackToken2, buyBackAddress2, buyBackToken2MidRouteAddress // _token0Info[]: token0Address, token0MidRouteAddress // _token1Info[]: token1Address, token1MidRouteAddress constructor( address _controller, bool _isAutoComp, address _farmContractAddress, uint256 _pid, address _wantAddress, address _earnedAddress, address _uniRouterAddress, address[] memory _buyBackToken1Info, address[] memory _buyBackToken2Info, address _token0, address _token1 ) public { operator = msg.sender; strategist = msg.sender; // to call earn if public not allowed isAutoComp = _isAutoComp; wantAddress = _wantAddress; if (_uniRouterAddress != address(0)) uniRouterAddress = _uniRouterAddress; buyBackToken1 = _buyBackToken1Info[0]; buyBackAddress1 = _buyBackToken1Info[1]; buyBackToken2 = _buyBackToken2Info[0]; buyBackAddress2 = _buyBackToken2Info[1]; if (isAutoComp) { token0Address = _token0; token1Address = _token1; farmContractAddress = _farmContractAddress; pid = _pid; earnedAddress = _earnedAddress; uniRouterAddress = _uniRouterAddress; } transferOwnership(_controller); } modifier onlyOperator() { require(operator == msg.sender, "BvaultsStrategy: caller is not the operator"); _; } modifier onlyStrategist() { require(strategist == msg.sender || operator == msg.sender, "BvaultsStrategy: caller is not the strategist"); _; } modifier onlyTimelock() { require(timelock == msg.sender, "BvaultsStrategy: caller is not timelock"); _; } function isAuthorised(address _account) public view returns (bool) { return (_account == operator) || (msg.sender == strategist) || (msg.sender == timelock); } // Receives new deposits from user function deposit(address, uint256 _wantAmt) public onlyOwner whenNotPaused returns (uint256) { IERC20(wantAddress).safeTransferFrom(address(msg.sender), address(this), _wantAmt); uint256 sharesAdded = _wantAmt; if (wantLockedTotal > 0 && sharesTotal > 0) { sharesAdded = _wantAmt.mul(sharesTotal).mul(entranceFeeFactor).div(wantLockedTotal).div(entranceFeeFactorMax); } sharesTotal = sharesTotal.add(sharesAdded); if (isAutoComp) { _farm(); } else { wantLockedTotal = wantLockedTotal.add(_wantAmt); } emit Deposit(_wantAmt); return sharesAdded; } function farm() public nonReentrant { _farm(); } function _farm() internal { uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); wantLockedTotal = wantLockedTotal.add(wantAmt); IERC20(wantAddress).safeIncreaseAllowance(farmContractAddress, wantAmt); IPancakeswapFarm(farmContractAddress).deposit(pid, wantAmt); emit Farm(wantAmt); } function withdraw(address, uint256 _wantAmt) public onlyOwner nonReentrant returns (uint256) { require(_wantAmt > 0, "BvaultsStrategy: !_wantAmt"); if (isAutoComp) { IPancakeswapFarm(farmContractAddress).withdraw(pid, _wantAmt); } uint256 wantAmt = IERC20(wantAddress).balanceOf(address(this)); if (_wantAmt > wantAmt) { _wantAmt = wantAmt; } if (wantLockedTotal < _wantAmt) { _wantAmt = wantLockedTotal; } uint256 sharesRemoved = _wantAmt.mul(sharesTotal).div(wantLockedTotal); if (sharesRemoved > sharesTotal) { sharesRemoved = sharesTotal; } sharesTotal = sharesTotal.sub(sharesRemoved); wantLockedTotal = wantLockedTotal.sub(_wantAmt); IERC20(wantAddress).safeTransfer(address(msg.sender), _wantAmt); emit Withdraw(_wantAmt); return sharesRemoved; } // 1. Harvest farm tokens // 2. Converts farm tokens into want tokens // 3. Deposits want tokens function earn() public whenNotPaused { require(isAutoComp, "BvaultsStrategy: !isAutoComp"); require(!notPublic || isAuthorised(msg.sender), "BvaultsStrategy: !authorised"); // Harvest farm tokens IPancakeswapFarm(farmContractAddress).withdraw(pid, 0); // Converts farm tokens into want tokens uint256 earnedAmt = IERC20(earnedAddress).balanceOf(address(this)); emit Earned(earnedAddress, earnedAmt); uint256 _distributeFee = distributeFees(earnedAmt); uint256 _buyBackAmt1 = buyBack1(earnedAmt); uint256 _buyBackAmt2 = buyBack2(earnedAmt); earnedAmt = earnedAmt.sub(_distributeFee).sub(_buyBackAmt1).sub(_buyBackAmt2); IERC20(earnedAddress).safeIncreaseAllowance(uniRouterAddress, earnedAmt); if (earnedAddress != token0Address) { // Swap half earned to token0 IPancakeRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(earnedAmt.div(2), 0, paths[earnedAddress][token0Address], address(this), now + 60); } if (earnedAddress != token1Address) { // Swap half earned to token1 IPancakeRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(earnedAmt.div(2), 0, paths[earnedAddress][token1Address], address(this), now + 60); } // Get want tokens, ie. add liquidity uint256 token0Amt = IERC20(token0Address).balanceOf(address(this)); uint256 token1Amt = IERC20(token1Address).balanceOf(address(this)); if (token0Amt > 0 && token1Amt > 0) { IERC20(token0Address).safeIncreaseAllowance(uniRouterAddress, token0Amt); IERC20(token1Address).safeIncreaseAllowance(uniRouterAddress, token1Amt); IPancakeRouter02(uniRouterAddress).addLiquidity(token0Address, token1Address, token0Amt, token1Amt, 0, 0, address(this), now + 60); emit Compound(token0Address, token0Amt, token1Address, token1Amt); } lastEarnBlock = block.number; _farm(); } function buyBack1(uint256 _earnedAmt) internal returns (uint256) { if (buyBackRate1 <= 0 || buyBackAddress1 == address(0)) { return 0; } uint256 _buyBackAmt = _earnedAmt.mul(buyBackRate1).div(buyBackRateMax); uint256 _before = IERC20(buyBackToken1).balanceOf(buyBackAddress1); if (earnedAddress != buyBackToken1) { IERC20(earnedAddress).safeIncreaseAllowance(uniRouterAddress, _buyBackAmt); IPancakeRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(_buyBackAmt, 0, paths[earnedAddress][buyBackToken1], buyBackAddress1, now + 60); } else { IERC20(earnedAddress).safeTransfer(buyBackAddress1, _buyBackAmt); } uint256 _after = IERC20(buyBackToken1).balanceOf(buyBackAddress1); uint256 _newReward = _after.sub(_before); emit BuyBack(earnedAddress, buyBackToken1, _buyBackAmt, _newReward, buyBackAddress1); return _buyBackAmt; } function buyBack2(uint256 _earnedAmt) internal returns (uint256) { if (buyBackRate2 <= 0 || buyBackAddress2 == address(0)) { return 0; } uint256 _buyBackAmt = _earnedAmt.mul(buyBackRate2).div(buyBackRateMax); uint256 _before = IERC20(buyBackToken2).balanceOf(buyBackAddress2); if (earnedAddress != buyBackToken2) { IERC20(earnedAddress).safeIncreaseAllowance(uniRouterAddress, _buyBackAmt); IPancakeRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(_buyBackAmt, 0, paths[earnedAddress][buyBackToken2], buyBackAddress2, now + 60); } else { IERC20(earnedAddress).safeTransfer(buyBackAddress2, _buyBackAmt); } uint256 _after = IERC20(buyBackToken2).balanceOf(buyBackAddress2); uint256 _newReward = _after.sub(_before); if (_newReward > 0) { ITreasury(buyBackAddress2).notifyExternalReward(_newReward); emit BuyBack(earnedAddress, buyBackToken2, _buyBackAmt, _newReward, buyBackAddress2); } return _buyBackAmt; } function distributeFees(uint256 _earnedAmt) internal returns (uint256 _fee) { if (_earnedAmt > 0) { // Performance fee if (controllerFee > 0) { _fee = _earnedAmt.mul(controllerFee).div(controllerFeeMax); IERC20(earnedAddress).safeTransfer(operator, _fee); emit DistributeFee(earnedAddress, _fee, operator); } } } function convertDustToEarned() public whenNotPaused { require(isAutoComp, "!isAutoComp"); // Converts dust tokens into earned tokens, which will be reinvested on the next earn(). // Converts token0 dust (if any) to earned tokens uint256 token0Amt = IERC20(token0Address).balanceOf(address(this)); if (token0Address != earnedAddress && token0Amt > 0) { IERC20(token0Address).safeIncreaseAllowance(uniRouterAddress, token0Amt); // Swap all dust tokens to earned tokens IPancakeRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(token0Amt, 0, paths[token0Address][earnedAddress], address(this), now + 60); emit ConvertDustToEarned(token0Address, earnedAddress, token0Amt); } // Converts token1 dust (if any) to earned tokens uint256 token1Amt = IERC20(token1Address).balanceOf(address(this)); if (token1Address != earnedAddress && token1Amt > 0) { IERC20(token1Address).safeIncreaseAllowance(uniRouterAddress, token1Amt); // Swap all dust tokens to earned tokens IPancakeRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(token1Amt, 0, paths[token1Address][earnedAddress], address(this), now + 60); emit ConvertDustToEarned(token1Address, earnedAddress, token1Amt); } } function uniExchangeRate(uint256 _tokenAmount, address[] memory _path) public view returns (uint256) { uint256[] memory amounts = IPancakeRouter02(uniRouterAddress).getAmountsOut(_tokenAmount, _path); return amounts[amounts.length - 1]; } function pendingHarvest() public view returns (uint256) { uint256 _earnedBal = IERC20(earnedAddress).balanceOf(address(this)); return IPancakeswapFarm(farmContractAddress).pendingBusd(pid, address(this)).add(_earnedBal); } function pendingHarvestDollarValue() public view returns (uint256) { uint256 _pending = pendingHarvest(); return _pending; } function pause() external onlyOperator { _pause(); } function unpause() external onlyOperator { _unpause(); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setStrategist(address _strategist) external onlyOperator { strategist = _strategist; } function setEntranceFeeFactor(uint256 _entranceFeeFactor) external onlyOperator { require(_entranceFeeFactor > entranceFeeFactorLL, "BvaultsStrategy: !safe - too low"); require(_entranceFeeFactor <= entranceFeeFactorMax, "BvaultsStrategy: !safe - too high"); entranceFeeFactor = _entranceFeeFactor; } function setControllerFee(uint256 _controllerFee) external onlyOperator { require(_controllerFee <= controllerFeeUL, "BvaultsStrategy: too high"); controllerFee = _controllerFee; } function setBuyBackRate1(uint256 _buyBackRate1) external onlyOperator { require(buyBackRate1 <= buyBackRateUL, "BvaultsStrategy: too high"); buyBackRate1 = _buyBackRate1; } function setBuyBackRate2(uint256 _buyBackRate2) external onlyOperator { require(buyBackRate2 <= buyBackRateUL, "BvaultsStrategy: too high"); buyBackRate2 = _buyBackRate2; } function setBuyBackAddress1(address _buyBackAddress1) external onlyOperator { require(buyBackAddress1 != address(0), "zero"); buyBackAddress1 = _buyBackAddress1; } function setBuyBackAddress2(address _buyBackAddress2) external onlyOperator { require(_buyBackAddress2 != address(0), "zero"); buyBackAddress2 = _buyBackAddress2; } function setNotPublic(bool _notPublic) external onlyOperator { notPublic = _notPublic; } function setMainPaths( address[] memory _earnedToBuyBackToken1Path, address[] memory _earnedToBuyBackToken2Path, address[] memory _earnedToToken0Path, address[] memory _earnedToToken1Path, address[] memory _earnedToBusdPath, address[] memory _token0ToEarnedPath, address[] memory _token1ToEarnedPath ) external onlyOperator { paths[earnedAddress][buyBackToken1] = _earnedToBuyBackToken1Path; paths[earnedAddress][buyBackToken2] = _earnedToBuyBackToken2Path; paths[earnedAddress][token0Address] = _earnedToToken0Path; paths[earnedAddress][token1Address] = _earnedToToken1Path; paths[earnedAddress][busdAddress] = _earnedToBusdPath; paths[token0Address][earnedAddress] = _token0ToEarnedPath; paths[token1Address][earnedAddress] = _token1ToEarnedPath; } function setPaths(address _inputToken, address _outputToken, address[] memory _path) external onlyOperator { paths[_inputToken][_outputToken] = _path; } function inCaseTokensGetStuck(address _token, uint256 _amount, address _to) external onlyOperator { require(_token != earnedAddress, "!safe"); require(_token != wantAddress, "!safe"); IERC20(_token).safeTransfer(_to, _amount); emit InCaseTokensGetStuck(_token, _amount, _to); } /* ========== EMERGENCY ========== */ function setTimelock(address _timelock) external onlyTimelock { timelock = _timelock; } /** * @dev This is from Timelock contract. */ function executeTransaction(address target, uint256 value, string memory signature, bytes memory data) external onlyTimelock returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value : value}(callData); require(success, "BvaultsStrategy::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(target, value, signature, data); return returnData; } }
SPDX-License-Identifier: MIT
interface ITreasury { function notifyExternalReward(uint256 _amount) external; }
1,777,680
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 24142, 266, 345, 22498, 288, 203, 565, 445, 5066, 6841, 17631, 1060, 12, 11890, 5034, 389, 8949, 13, 3903, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-20 */ // Sources flattened with hardhat v2.4.3 https://hardhat.org // File openzeppelin-solidity/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File openzeppelin-solidity/contracts/utils/introspection/[email protected] 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-solidity/contracts/utils/introspection/[email protected] 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-solidity/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File openzeppelin-solidity/contracts/governance/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockController is AccessControl { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`. */ constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); // solhint-disable-next-line not-rely-on-time return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, datas, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); // solhint-disable-next-line not-rely-on-time _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'proposer' role. */ function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 predecessor) private view { require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private { // solhint-disable-next-line avoid-low-level-calls (bool success,) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } } // File contracts/interfaces/ISwapRouter.sol pragma solidity 0.8.6; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); // solhint-disable-next-line func-name-mixedcase function WETH9() external pure returns (address); } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File openzeppelin-solidity/contracts/token/ERC20/utils/[email protected] pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File openzeppelin-solidity/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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, 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File openzeppelin-solidity/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/HATToken.sol pragma solidity 0.8.6; contract HATToken is IERC20 { struct PendingMinter { uint256 seedAmount; uint256 setMinterPendingAt; } /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "hats.finance"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "HAT"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public override totalSupply; address public governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public immutable timeLockDelay; uint256 public constant CAP = 10000000e18; /// @notice Address which may mint new tokens /// minter -> minting seedAmount mapping (address => uint256) public minters; /// @notice Address which may mint new tokens /// minter -> minting seedAmount mapping (address => PendingMinter) public pendingMinters; // @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; // @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice An event thats emitted when a new minter address is pending event MinterPending(address indexed minter, uint256 seedAmount, uint256 at); /// @notice An event thats emitted when the minter address is changed event MinterChanged(address indexed minter, uint256 seedAmount); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed oldGovernance, address indexed newGovernance, uint256 at); /// @notice An event thats emitted when a new governance address is set event GovernanceChanged(address indexed oldGovernance, address indexed newGovernance); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Construct a new HAT token */ // solhint-disable-next-line func-visibility constructor(address _governance, uint256 _timeLockDelay) { governance = _governance; timeLockDelay = _timeLockDelay; } function setPendingGovernance(address _governance) external { require(msg.sender == governance, "HAT:!governance"); require(_governance != address(0), "HAT:!_governance"); governancePending = _governance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(governance, _governance, setGovernancePendingAt); } function confirmGovernance() external { require(msg.sender == governance, "HAT:!governance"); require(setGovernancePendingAt > 0, "HAT:!governancePending"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > timeLockDelay, "HAT: cannot confirm governance at this time"); emit GovernanceChanged(governance, governancePending); governance = governancePending; setGovernancePendingAt = 0; } function setPendingMinter(address _minter, uint256 _cap) external { require(msg.sender == governance, "HAT::!governance"); pendingMinters[_minter].seedAmount = _cap; // solhint-disable-next-line not-rely-on-time pendingMinters[_minter].setMinterPendingAt = block.timestamp; emit MinterPending(_minter, _cap, pendingMinters[_minter].setMinterPendingAt); } function confirmMinter(address _minter) external { require(msg.sender == governance, "HAT::mint: only the governance can confirm minter"); require(pendingMinters[_minter].setMinterPendingAt > 0, "HAT:: no pending minter was set"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - pendingMinters[_minter].setMinterPendingAt > timeLockDelay, "HATToken: cannot confirm at this time"); minters[_minter] = pendingMinters[_minter].seedAmount; pendingMinters[_minter].setMinterPendingAt = 0; emit MinterChanged(_minter, pendingMinters[_minter].seedAmount); } function burn(uint256 _amount) external { return _burn(msg.sender, _amount); } function mint(address _account, uint _amount) external { require(minters[msg.sender] >= _amount, "HATToken: amount greater than limitation"); minters[msg.sender] = SafeMath.sub(minters[msg.sender], _amount); _mint(_account, _amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external override view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external override returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, 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, uint addedValue) external virtual returns (bool) { require(spender != address(0), "HAT: increaseAllowance to the zero address"); uint96 valueToAdd = safe96(addedValue, "HAT::increaseAllowance: addedValue exceeds 96 bits"); allowances[msg.sender][spender] = add96(allowances[msg.sender][spender], valueToAdd, "HAT::increaseAllowance: overflows"); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); 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, uint subtractedValue) external virtual returns (bool) { require(spender != address(0), "HAT: decreaseAllowance to the zero address"); uint96 valueTosubtract = safe96(subtractedValue, "HAT::decreaseAllowance: subtractedValue exceeds 96 bits"); allowances[msg.sender][spender] = sub96(allowances[msg.sender][spender], valueTosubtract, "HAT::decreaseAllowance: spender allowance is less than subtractedValue"); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "HAT::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "HAT::permit: invalid signature"); require(signatory == owner, "HAT::permit: unauthorized"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "HAT::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view override returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external override returns (bool) { uint96 amount = safe96(rawAmount, "HAT::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external override returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96(spenderAllowance, amount, "HAT::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "HAT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "HAT::delegateBySig: invalid nonce"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= expiry, "HAT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint96) { require(blockNumber < block.number, "HAT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function _mint(address dst, uint rawAmount) internal { require(dst != address(0), "HAT::mint: cannot transfer to the zero address"); require(SafeMath.add(totalSupply, rawAmount) <= CAP, "ERC20Capped: CAP exceeded"); // mint the amount uint96 amount = safe96(rawAmount, "HAT::mint: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "HAT::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * Burn tokens * @param src The address of the source account * @param rawAmount The number of tokens to be burned */ function _burn(address src, uint rawAmount) internal { require(src != address(0), "HAT::burn: cannot burn to the zero address"); // burn the amount uint96 amount = safe96(rawAmount, "HAT::burn: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.sub(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits"); // reduce the amount from src address balances[src] = sub96(balances[src], amount, "HAT::burn: burn amount exceeds balance"); emit Transfer(src, address(0), amount); // move delegates _moveDelegates(delegates[src], address(0), amount); } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "HAT::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "HAT::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "HAT::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "HAT::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "HAT::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "HAT::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "HAT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // File openzeppelin-solidity/contracts/security/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/HATMaster.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATMaster is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // The user share of the pool based on the amount of lpToken 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 HATs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.rewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `rewardPerShare` (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. } struct PoolUpdate { uint256 blockNumber;// update blocknumber uint256 totalAllocPoint; //totalAllocPoint } struct RewardsSplit { //the percentage of the total reward to reward the hacker via vesting contract(claim reported) uint256 hackerVestedReward; //the percentage of the total reward to reward the hacker(claim reported) uint256 hackerReward; // the percentage of the total reward to be sent to the committee uint256 committeeReward; // the percentage of the total reward to be swap to HAT and to be burned uint256 swapAndBurn; // the percentage of the total reward to be swap to HAT and sent to governance uint256 governanceHatReward; // the percentage of the total reward to be swap to HAT and sent to the hacker uint256 hackerHatReward; } // Info of each pool. struct PoolInfo { IERC20 lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 rewardPerShare; uint256 totalUsersAmount; uint256 lastProcessedTotalAllocPoint; uint256 balance; } // Info of each pool. struct PoolReward { RewardsSplit rewardsSplit; uint256[] rewardsLevels; bool committeeCheckIn; uint256 vestingDuration; uint256 vestingPeriods; } HATToken public immutable HAT; uint256 public immutable REWARD_PER_BLOCK; uint256 public immutable START_BLOCK; uint256 public immutable MULTIPLIER_PERIOD; // Info of each pool. PoolInfo[] public poolInfo; PoolUpdate[] public globalPoolUpdates; mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo // Info of each user that stakes LP tokens. pid => user address => info mapping (uint256 => mapping (address => UserInfo)) public userInfo; //pid -> PoolReward mapping (uint256=>PoolReward) internal poolsRewards; 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 SendReward(address indexed user, uint256 indexed pid, uint256 amount, uint256 requestedAmount); event MassUpdatePools(uint256 _fromPid, uint256 _toPid); constructor( HATToken _hat, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _multiplierPeriod // solhint-disable-next-line func-visibility ) { HAT = _hat; REWARD_PER_BLOCK = _rewardPerBlock; START_BLOCK = _startBlock; MULTIPLIER_PERIOD = _multiplierPeriod; } /** * @dev massUpdatePools - Update reward variables for all pools * Be careful of gas spending! * @param _fromPid update pools range from this pool id * @param _toPid update pools range to this pool id */ function massUpdatePools(uint256 _fromPid, uint256 _toPid) external { require(_toPid <= poolInfo.length, "pool range is too big"); require(_fromPid <= _toPid, "invalid pool range"); for (uint256 pid = _fromPid; pid < _toPid; ++pid) { updatePool(pid); } emit MassUpdatePools(_fromPid, _toPid); } function claimReward(uint256 _pid) external { _deposit(_pid, 0); } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 lastRewardBlock = pool.lastRewardBlock; if (block.number <= lastRewardBlock) { return; } uint256 totalUsersAmount = pool.totalUsersAmount; uint256 lastPoolUpdate = globalPoolUpdates.length-1; if (totalUsersAmount == 0) { pool.lastRewardBlock = block.number; pool.lastProcessedTotalAllocPoint = lastPoolUpdate; return; } uint256 reward = calcPoolReward(_pid, lastRewardBlock, lastPoolUpdate); uint256 amountCanMint = HAT.minters(address(this)); reward = amountCanMint < reward ? amountCanMint : reward; if (reward > 0) { HAT.mint(address(this), reward); } pool.rewardPerShare = pool.rewardPerShare.add(reward.mul(1e12).div(totalUsersAmount)); pool.lastRewardBlock = block.number; pool.lastProcessedTotalAllocPoint = lastPoolUpdate; } /** * @dev getMultiplier - multiply blocks with relevant multiplier for specific range * @param _from range's from block * @param _to range's to block * will revert if from < START_BLOCK or _to < _from */ function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256 result) { uint256[25] memory rewardMultipliers = [uint256(4413), 4413, 8825, 7788, 6873, 6065, 5353, 4724, 4169, 3679, 3247, 2865, 2528, 2231, 1969, 1738, 1534, 1353, 1194, 1054, 930, 821, 724, 639, 0]; uint256 max = rewardMultipliers.length; uint256 i = (_from - START_BLOCK) / MULTIPLIER_PERIOD + 1; for (; i < max; i++) { uint256 endBlock = MULTIPLIER_PERIOD * i + START_BLOCK; if (_to <= endBlock) { break; } result += (endBlock - _from) * rewardMultipliers[i-1]; _from = endBlock; } result += (_to - _from) * rewardMultipliers[i > max ? (max-1) : (i-1)]; } function getRewardForBlocksRange(uint256 _from, uint256 _to, uint256 _allocPoint, uint256 _totalAllocPoint) public view returns (uint256 reward) { if (_totalAllocPoint > 0) { reward = getMultiplier(_from, _to).mul(REWARD_PER_BLOCK).mul(_allocPoint).div(_totalAllocPoint).div(100); } } /** * @dev calcPoolReward - * calculate rewards for a pool by iterating over the history of totalAllocPoints updates. * and sum up all rewards periods from pool.lastRewardBlock till current block number. * @param _pid pool id * @param _from block starting calculation * @param _lastPoolUpdate lastPoolUpdate * @return reward */ function calcPoolReward(uint256 _pid, uint256 _from, uint256 _lastPoolUpdate) public view returns(uint256 reward) { uint256 poolAllocPoint = poolInfo[_pid].allocPoint; uint256 i = poolInfo[_pid].lastProcessedTotalAllocPoint; for (; i < _lastPoolUpdate; i++) { uint256 nextUpdateBlock = globalPoolUpdates[i+1].blockNumber; reward = reward.add(getRewardForBlocksRange(_from, nextUpdateBlock, poolAllocPoint, globalPoolUpdates[i].totalAllocPoint)); _from = nextUpdateBlock; } return reward.add(getRewardForBlocksRange(_from, block.number, poolAllocPoint, globalPoolUpdates[i].totalAllocPoint)); } function _deposit(uint256 _pid, uint256 _amount) internal nonReentrant { require(poolsRewards[_pid].committeeCheckIn, "committee not checked in yet"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeTransferReward(msg.sender, pending, _pid); } } if (_amount > 0) { uint256 lpSupply = pool.balance; pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.balance = pool.balance.add(_amount); uint256 factoredAmount = _amount; if (pool.totalUsersAmount > 0) { factoredAmount = pool.totalUsersAmount.mul(_amount).div(lpSupply); } user.amount = user.amount.add(factoredAmount); pool.totalUsersAmount = pool.totalUsersAmount.add(factoredAmount); } user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function _withdraw(uint256 _pid, uint256 _amount) internal nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not enough user balance"); updatePool(_pid); uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeTransferReward(msg.sender, pending, _pid); } if (_amount > 0) { user.amount = user.amount.sub(_amount); uint256 amountToWithdraw = _amount.mul(pool.balance).div(pool.totalUsersAmount); pool.balance = pool.balance.sub(amountToWithdraw); pool.lpToken.safeTransfer(msg.sender, amountToWithdraw); pool.totalUsersAmount = pool.totalUsersAmount.sub(_amount); } user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function _emergencyWithdraw(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "user.amount = 0"); uint256 factoredBalance = user.amount.mul(pool.balance).div(pool.totalUsersAmount); pool.totalUsersAmount = pool.totalUsersAmount.sub(user.amount); user.amount = 0; user.rewardDebt = 0; pool.balance = pool.balance.sub(factoredBalance); pool.lpToken.safeTransfer(msg.sender, factoredBalance); emit EmergencyWithdraw(msg.sender, _pid, factoredBalance); } // -------- For manage pool --------- function add(uint256 _allocPoint, IERC20 _lpToken) internal { require(poolId1[address(_lpToken)] == 0, "HATMaster::add: lpToken is already in pool"); poolId1[address(_lpToken)] = poolInfo.length + 1; uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK; uint256 totalAllocPoint = (globalPoolUpdates.length == 0) ? _allocPoint : globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint.add(_allocPoint); if (globalPoolUpdates.length > 0 && globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) { //already update in this block globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint; } else { globalPoolUpdates.push(PoolUpdate({ blockNumber: block.number, totalAllocPoint: totalAllocPoint })); } poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, rewardPerShare: 0, totalUsersAmount: 0, lastProcessedTotalAllocPoint: globalPoolUpdates.length-1, balance: 0 })); } function set(uint256 _pid, uint256 _allocPoint) internal { updatePool(_pid); uint256 totalAllocPoint = globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint .sub(poolInfo[_pid].allocPoint).add(_allocPoint); if (globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) { //already update in this block globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint; } else { globalPoolUpdates.push(PoolUpdate({ blockNumber: block.number, totalAllocPoint: totalAllocPoint })); } poolInfo[_pid].allocPoint = _allocPoint; } // Safe HAT transfer function, just in case if rounding error causes pool to not have enough HATs. function safeTransferReward(address _to, uint256 _amount, uint256 _pid) internal { uint256 hatBalance = HAT.balanceOf(address(this)); if (_amount > hatBalance) { HAT.transfer(_to, hatBalance); emit SendReward(_to, _pid, hatBalance, _amount); } else { HAT.transfer(_to, _amount); emit SendReward(_to, _pid, _amount, _amount); } } } // File contracts/tokenlock/ITokenLock.sol pragma solidity 0.8.6; pragma experimental ABIEncoderV2; interface ITokenLock { enum Revocability { NotSet, Enabled, Disabled } // -- Balances -- function currentBalance() external view returns (uint256); // -- Time & Periods -- function currentTime() external view returns (uint256); function duration() external view returns (uint256); function sinceStartTime() external view returns (uint256); function amountPerPeriod() external view returns (uint256); function periodDuration() external view returns (uint256); function currentPeriod() external view returns (uint256); function passedPeriods() external view returns (uint256); // -- Locking & Release Schedule -- function availableAmount() external view returns (uint256); function vestedAmount() external view returns (uint256); function releasableAmount() external view returns (uint256); function totalOutstandingAmount() external view returns (uint256); function surplusAmount() external view returns (uint256); // -- Value Transfer -- function release() external; function withdrawSurplus(uint256 _amount) external; function revoke() external; } // File contracts/tokenlock/ITokenLockFactory.sol pragma solidity 0.8.6; interface ITokenLockFactory { // -- Factory -- function setMasterCopy(address _masterCopy) external; function createTokenLock( address _token, address _owner, address _beneficiary, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, ITokenLock.Revocability _revocable, bool _canDelegate ) external returns(address contractAddress); } // File contracts/Governable.sol pragma solidity 0.8.6; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an governance) that can be granted exclusive access to * specific functions. * * The governance account will be passed on initialization of the contract. This * can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}. * * This module is used through inheritance. It will make available the modifier * `onlyGovernance`, which can be applied to your functions to restrict their use to * the governance. */ contract Governable { address private _governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public constant TIME_LOCK_DELAY = 2 days; /// @notice An event thats emitted when a new governance address is set event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at); /** * @dev Throws if called by any account other than the governance. */ modifier onlyGovernance() { require(msg.sender == _governance, "only governance"); _; } /** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */ function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); } /** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */ function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; } /** * @dev Returns the address of the current governance. */ function governance() public view returns (address) { return _governance; } /** * @dev Initializes the contract setting the initial governance. */ function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); } } // File contracts/HATVaults.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATVaults is Governable, HATMaster { using SafeMath for uint256; using SafeERC20 for IERC20; struct PendingApproval { address beneficiary; uint256 severity; address approver; } struct ClaimReward { uint256 hackerVestedReward; uint256 hackerReward; uint256 committeeReward; uint256 swapAndBurn; uint256 governanceHatReward; uint256 hackerHatReward; } struct PendingRewardsLevels { uint256 timestamp; uint256[] rewardsLevels; } struct GeneralParameters { uint256 hatVestingDuration; uint256 hatVestingPeriods; uint256 withdrawPeriod; uint256 safetyPeriod; //withdraw disable period in seconds uint256 setRewardsLevelsDelay; uint256 withdrawRequestEnablePeriod; uint256 withdrawRequestPendingPeriod; uint256 claimFee; //claim fee in ETH } //pid -> committee address mapping(uint256=>address) public committees; mapping(address => uint256) public swapAndBurns; //hackerAddress ->(token->amount) mapping(address => mapping(address => uint256)) public hackersHatRewards; //token -> amount mapping(address => uint256) public governanceHatRewards; //pid -> PendingApproval mapping(uint256 => PendingApproval) public pendingApprovals; //poolId -> (address -> requestTime) mapping(uint256 => mapping(address => uint256)) public withdrawRequests; //poolId -> PendingRewardsLevels mapping(uint256 => PendingRewardsLevels) public pendingRewardsLevels; mapping(uint256 => bool) public poolDepositPause; GeneralParameters public generalParameters; uint256 internal constant REWARDS_LEVEL_DENOMINATOR = 10000; ITokenLockFactory public immutable tokenLockFactory; ISwapRouter public immutable uniSwapRouter; uint256 public constant MINIMUM_DEPOSIT = 1e6; modifier onlyCommittee(uint256 _pid) { require(committees[_pid] == msg.sender, "only committee"); _; } modifier noPendingApproval(uint256 _pid) { require(pendingApprovals[_pid].beneficiary == address(0), "pending approval exist"); _; } modifier noSafetyPeriod() { //disable withdraw for safetyPeriod (e.g 1 hour) each withdrawPeriod(e.g 11 hours) // solhint-disable-next-line not-rely-on-time require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) < generalParameters.withdrawPeriod, "safety period"); _; } event SetCommittee(uint256 indexed _pid, address indexed _committee); event AddPool(uint256 indexed _pid, uint256 indexed _allocPoint, address indexed _lpToken, address _committee, string _descriptionHash, uint256[] _rewardsLevels, RewardsSplit _rewardsSplit, uint256 _rewardVestingDuration, uint256 _rewardVestingPeriods); event SetPool(uint256 indexed _pid, uint256 indexed _allocPoint, bool indexed _registered, string _descriptionHash); event Claim(address indexed _claimer, string _descriptionHash); event SetRewardsSplit(uint256 indexed _pid, RewardsSplit _rewardsSplit); event SetRewardsLevels(uint256 indexed _pid, uint256[] _rewardsLevels); event PendingRewardsLevelsLog(uint256 indexed _pid, uint256[] _rewardsLevels, uint256 _timeStamp); event SwapAndSend(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _amountSwaped, uint256 _amountReceived, address _tokenLock); event SwapAndBurn(uint256 indexed _pid, uint256 indexed _amountSwaped, uint256 indexed _amountBurned); event SetVestingParams(uint256 indexed _pid, uint256 indexed _duration, uint256 indexed _periods); event SetHatVestingParams(uint256 indexed _duration, uint256 indexed _periods); event ClaimApprove(address indexed _approver, uint256 indexed _pid, address indexed _beneficiary, uint256 _severity, address _tokenLock, ClaimReward _claimReward); event PendingApprovalLog(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _severity, address _approver); event WithdrawRequest(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _withdrawEnableTime); event SetWithdrawSafetyPeriod(uint256 indexed _withdrawPeriod, uint256 indexed _safetyPeriod); event RewardDepositors(uint256 indexed _pid, uint256 indexed _amount); /** * @dev constructor - * @param _rewardsToken the reward token address (HAT) * @param _rewardPerBlock the reward amount per block the contract will reward pools * @param _startBlock start block of of which the contract will start rewarding from. * @param _multiplierPeriod a fix period value. each period will have its own multiplier value. * which set the reward for each period. e.g a value of 100000 means that each such period is 100000 blocks. * @param _hatGovernance the governance address. * Some of the contracts functions are limited only to governance : * addPool,setPool,dismissPendingApprovalClaim,approveClaim, * setHatVestingParams,setVestingParams,setRewardsSplit * @param _uniSwapRouter uni swap v3 router to be used to swap tokens for HAT token. * @param _tokenLockFactory address of the token lock factory to be used * to create a vesting contract for the approved claim reporter. */ constructor( address _rewardsToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _multiplierPeriod, address _hatGovernance, ISwapRouter _uniSwapRouter, ITokenLockFactory _tokenLockFactory // solhint-disable-next-line func-visibility ) HATMaster(HATToken(_rewardsToken), _rewardPerBlock, _startBlock, _multiplierPeriod) { Governable.initialize(_hatGovernance); uniSwapRouter = _uniSwapRouter; tokenLockFactory = _tokenLockFactory; generalParameters = GeneralParameters({ hatVestingDuration: 90 days, hatVestingPeriods:90, withdrawPeriod: 11 hours, safetyPeriod: 1 hours, setRewardsLevelsDelay: 2 days, withdrawRequestEnablePeriod: 7 days, withdrawRequestPendingPeriod: 7 days, claimFee: 0 }); } /** * @dev pendingApprovalClaim - called by a committee to set a pending approval claim. * The pending approval need to be approved or dismissed by the hats governance. * This function should be called only on a safety period, where withdrawn is disable. * Upon a call to this function by the committee the pool withdrawn will be disable * till governance will approve or dismiss this pending approval. * @param _pid pool id * @param _beneficiary the approval claim beneficiary * @param _severity approval claim severity */ function pendingApprovalClaim(uint256 _pid, address _beneficiary, uint256 _severity) external onlyCommittee(_pid) noPendingApproval(_pid) { require(_beneficiary != address(0), "beneficiary is zero"); // solhint-disable-next-line not-rely-on-time require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) >= generalParameters.withdrawPeriod, "none safety period"); require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range"); pendingApprovals[_pid] = PendingApproval({ beneficiary: _beneficiary, severity: _severity, approver: msg.sender }); emit PendingApprovalLog(_pid, _beneficiary, _severity, msg.sender); } /** * @dev setWithdrawRequestParams - called by hats governance to set withdraw request params * @param _withdrawRequestPendingPeriod - the time period where the withdraw request is pending. * @param _withdrawRequestEnablePeriod - the time period where the withdraw is enable for a withdraw request. */ function setWithdrawRequestParams(uint256 _withdrawRequestPendingPeriod, uint256 _withdrawRequestEnablePeriod) external onlyGovernance { generalParameters.withdrawRequestPendingPeriod = _withdrawRequestPendingPeriod; generalParameters.withdrawRequestEnablePeriod = _withdrawRequestEnablePeriod; } /** * @dev dismissPendingApprovalClaim - called by hats governance to dismiss a pending approval claim. * @param _pid pool id */ function dismissPendingApprovalClaim(uint256 _pid) external onlyGovernance { delete pendingApprovals[_pid]; } /** * @dev approveClaim - called by hats governance to approve a pending approval claim. * @param _pid pool id */ function approveClaim(uint256 _pid) external onlyGovernance nonReentrant { require(pendingApprovals[_pid].beneficiary != address(0), "no pending approval"); PoolReward storage poolReward = poolsRewards[_pid]; PendingApproval memory pendingApproval = pendingApprovals[_pid]; delete pendingApprovals[_pid]; IERC20 lpToken = poolInfo[_pid].lpToken; ClaimReward memory claimRewards = calcClaimRewards(_pid, pendingApproval.severity); poolInfo[_pid].balance = poolInfo[_pid].balance.sub( claimRewards.hackerReward .add(claimRewards.hackerVestedReward) .add(claimRewards.committeeReward) .add(claimRewards.swapAndBurn) .add(claimRewards.hackerHatReward) .add(claimRewards.governanceHatReward)); address tokenLock; if (claimRewards.hackerVestedReward > 0) { //hacker get its reward to a vesting contract tokenLock = tokenLockFactory.createTokenLock( address(lpToken), 0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing. pendingApproval.beneficiary, claimRewards.hackerVestedReward, // solhint-disable-next-line not-rely-on-time block.timestamp, //start // solhint-disable-next-line not-rely-on-time block.timestamp + poolReward.vestingDuration, //end poolReward.vestingPeriods, 0, //no release start 0, //no cliff ITokenLock.Revocability.Disabled, false ); lpToken.safeTransfer(tokenLock, claimRewards.hackerVestedReward); } lpToken.safeTransfer(pendingApproval.beneficiary, claimRewards.hackerReward); lpToken.safeTransfer(pendingApproval.approver, claimRewards.committeeReward); //storing the amount of token which can be swap and burned so it could be swapAndBurn in a seperate tx. swapAndBurns[address(lpToken)] = swapAndBurns[address(lpToken)].add(claimRewards.swapAndBurn); governanceHatRewards[address(lpToken)] = governanceHatRewards[address(lpToken)].add(claimRewards.governanceHatReward); hackersHatRewards[pendingApproval.beneficiary][address(lpToken)] = hackersHatRewards[pendingApproval.beneficiary][address(lpToken)].add(claimRewards.hackerHatReward); emit ClaimApprove(msg.sender, _pid, pendingApproval.beneficiary, pendingApproval.severity, tokenLock, claimRewards); assert(poolInfo[_pid].balance > 0); } /** * @dev rewardDepositors - add funds to pool to reward depositors. * The funds will be given to depositors pro rata upon withdraw * @param _pid pool id * @param _amount amount to add */ function rewardDepositors(uint256 _pid, uint256 _amount) external { require(poolInfo[_pid].balance.add(_amount).div(MINIMUM_DEPOSIT) < poolInfo[_pid].totalUsersAmount, "amount to reward is too big"); poolInfo[_pid].lpToken.safeTransferFrom(msg.sender, address(this), _amount); poolInfo[_pid].balance = poolInfo[_pid].balance.add(_amount); emit RewardDepositors(_pid, _amount); } /** * @dev setClaimFee - called by hats governance to set claim fee * @param _fee claim fee in ETH */ function setClaimFee(uint256 _fee) external onlyGovernance { generalParameters.claimFee = _fee; } /** * @dev setWithdrawSafetyPeriod - called by hats governance to set Withdraw Period * @param _withdrawPeriod withdraw enable period * @param _safetyPeriod withdraw disable period */ function setWithdrawSafetyPeriod(uint256 _withdrawPeriod, uint256 _safetyPeriod) external onlyGovernance { generalParameters.withdrawPeriod = _withdrawPeriod; generalParameters.safetyPeriod = _safetyPeriod; emit SetWithdrawSafetyPeriod(generalParameters.withdrawPeriod, generalParameters.safetyPeriod); } //_descriptionHash - a hash of an ipfs encrypted file which describe the claim. // this can be use later on by the claimer to prove her claim function claim(string memory _descriptionHash) external payable { if (generalParameters.claimFee > 0) { require(msg.value >= generalParameters.claimFee, "not enough fee payed"); // solhint-disable-next-line indent payable(governance()).transfer(msg.value); } emit Claim(msg.sender, _descriptionHash); } /** * @dev setVestingParams - set pool vesting params for rewarding claim reporter with the pool token * @param _pid pool id * @param _duration duration of the vesting period * @param _periods the vesting periods */ function setVestingParams(uint256 _pid, uint256 _duration, uint256 _periods) external onlyGovernance { require(_duration < 120 days, "vesting duration is too long"); require(_periods > 0, "vesting periods cannot be zero"); require(_duration >= _periods, "vesting duration smaller than periods"); poolsRewards[_pid].vestingDuration = _duration; poolsRewards[_pid].vestingPeriods = _periods; emit SetVestingParams(_pid, _duration, _periods); } /** * @dev setHatVestingParams - set HAT vesting params for rewarding claim reporter with HAT token * the function can be called only by governance. * @param _duration duration of the vesting period * @param _periods the vesting periods */ function setHatVestingParams(uint256 _duration, uint256 _periods) external onlyGovernance { require(_duration < 180 days, "vesting duration is too long"); require(_periods > 0, "vesting periods cannot be zero"); require(_duration >= _periods, "vesting duration smaller than periods"); generalParameters.hatVestingDuration = _duration; generalParameters.hatVestingPeriods = _periods; emit SetHatVestingParams(_duration, _periods); } /** * @dev setRewardsSplit - set the pool token rewards split upon an approval * the function can be called only by governance. * the sum of the rewards split should be less than 10000 (less than 100%) * @param _pid pool id * @param _rewardsSplit split * and sent to the hacker(claim reported) */ function setRewardsSplit(uint256 _pid, RewardsSplit memory _rewardsSplit) external onlyGovernance noPendingApproval(_pid) noSafetyPeriod { validateSplit(_rewardsSplit); poolsRewards[_pid].rewardsSplit = _rewardsSplit; emit SetRewardsSplit(_pid, _rewardsSplit); } /** * @dev setRewardsLevelsDelay - set the timelock delay for setting rewars level * @param _delay time delay */ function setRewardsLevelsDelay(uint256 _delay) external onlyGovernance { require(_delay >= 2 days, "delay is too short"); generalParameters.setRewardsLevelsDelay = _delay; } /** * @dev setPendingRewardsLevels - set pending request to set pool token rewards level. * the reward level represent the percentage of the pool's token which will be split as a reward. * the function can be called only by the pool committee. * cannot be called if there already pending approval. * each level should be less than 10000 * @param _pid pool id * @param _rewardsLevels the reward levels array */ function setPendingRewardsLevels(uint256 _pid, uint256[] memory _rewardsLevels) external onlyCommittee(_pid) noPendingApproval(_pid) { pendingRewardsLevels[_pid].rewardsLevels = checkRewardsLevels(_rewardsLevels); // solhint-disable-next-line not-rely-on-time pendingRewardsLevels[_pid].timestamp = block.timestamp; emit PendingRewardsLevelsLog(_pid, _rewardsLevels, pendingRewardsLevels[_pid].timestamp); } /** * @dev setRewardsLevels - set the pool token rewards level of already pending set rewards level. * see pendingRewardsLevels * the reward level represent the percentage of the pool's token which will be split as a reward. * the function can be called only by the pool committee. * cannot be called if there already pending approval. * each level should be less than 10000 * @param _pid pool id */ function setRewardsLevels(uint256 _pid) external onlyCommittee(_pid) noPendingApproval(_pid) { require(pendingRewardsLevels[_pid].timestamp > 0, "no pending set rewards levels"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - pendingRewardsLevels[_pid].timestamp > generalParameters.setRewardsLevelsDelay, "cannot confirm setRewardsLevels at this time"); poolsRewards[_pid].rewardsLevels = pendingRewardsLevels[_pid].rewardsLevels; delete pendingRewardsLevels[_pid]; emit SetRewardsLevels(_pid, poolsRewards[_pid].rewardsLevels); } /** * @dev committeeCheckIn - committee check in. * deposit is enable only after committee check in * @param _pid pool id */ function committeeCheckIn(uint256 _pid) external onlyCommittee(_pid) { poolsRewards[_pid].committeeCheckIn = true; } /** * @dev setCommittee - set new committee address. * @param _pid pool id * @param _committee new committee address */ function setCommittee(uint256 _pid, address _committee) external { require(_committee != address(0), "committee is zero"); //governance can update committee only if committee was not checked in yet. if (msg.sender == governance() && committees[_pid] != msg.sender) { require(!poolsRewards[_pid].committeeCheckIn, "Committee already checked in"); } else { require(committees[_pid] == msg.sender, "Only committee"); } committees[_pid] = _committee; emit SetCommittee(_pid, _committee); } /** * @dev addPool - only Governance * @param _allocPoint the pool allocation point * @param _lpToken pool token * @param _committee pool committee address * @param _rewardsLevels pool reward levels(sevirities) each level is a number between 0 and 10000. * @param _rewardsSplit pool reward split. each entry is a number between 0 and 10000. total splits should be equal to 10000 * @param _descriptionHash the hash of the pool description. * @param _rewardVestingParams vesting params * _rewardVestingParams[0] - vesting duration * _rewardVestingParams[1] - vesting periods */ function addPool(uint256 _allocPoint, address _lpToken, address _committee, uint256[] memory _rewardsLevels, RewardsSplit memory _rewardsSplit, string memory _descriptionHash, uint256[2] memory _rewardVestingParams) external onlyGovernance { require(_rewardVestingParams[0] < 120 days, "vesting duration is too long"); require(_rewardVestingParams[1] > 0, "vesting periods cannot be zero"); require(_rewardVestingParams[0] >= _rewardVestingParams[1], "vesting duration smaller than periods"); require(_committee != address(0), "committee is zero"); add(_allocPoint, IERC20(_lpToken)); uint256 poolId = poolInfo.length-1; committees[poolId] = _committee; uint256[] memory rewardsLevels = checkRewardsLevels(_rewardsLevels); RewardsSplit memory rewardsSplit = (_rewardsSplit.hackerVestedReward == 0 && _rewardsSplit.hackerReward == 0) ? getDefaultRewardsSplit() : _rewardsSplit; validateSplit(rewardsSplit); poolsRewards[poolId] = PoolReward({ rewardsLevels: rewardsLevels, rewardsSplit: rewardsSplit, committeeCheckIn: false, vestingDuration: _rewardVestingParams[0], vestingPeriods: _rewardVestingParams[1] }); emit AddPool(poolId, _allocPoint, address(_lpToken), _committee, _descriptionHash, rewardsLevels, rewardsSplit, _rewardVestingParams[0], _rewardVestingParams[1]); } /** * @dev setPool * @param _pid the pool id * @param _allocPoint the pool allocation point * @param _registered does this pool is registered (default true). * @param _depositPause pause pool deposit (default false). * This parameter can be used by the UI to include or exclude the pool * @param _descriptionHash the hash of the pool description. */ function setPool(uint256 _pid, uint256 _allocPoint, bool _registered, bool _depositPause, string memory _descriptionHash) external onlyGovernance { require(poolInfo[_pid].lpToken != IERC20(address(0)), "pool does not exist"); set(_pid, _allocPoint); poolDepositPause[_pid] = _depositPause; emit SetPool(_pid, _allocPoint, _registered, _descriptionHash); } /** * @dev swapBurnSend swap lptoken to HAT. * send to beneficiary and governance its hats rewards . * burn the rest of HAT. * only governance are authorized to call this function. * @param _pid the pool id * @param _beneficiary beneficiary * @param _amountOutMinimum minimum output of HATs at swap * @param _fees the fees for the multi path swap **/ function swapBurnSend(uint256 _pid, address _beneficiary, uint256 _amountOutMinimum, uint24[2] memory _fees) external onlyGovernance { IERC20 token = poolInfo[_pid].lpToken; uint256 amountToSwapAndBurn = swapAndBurns[address(token)]; uint256 amountForHackersHatRewards = hackersHatRewards[_beneficiary][address(token)]; uint256 amount = amountToSwapAndBurn.add(amountForHackersHatRewards).add(governanceHatRewards[address(token)]); require(amount > 0, "amount is zero"); swapAndBurns[address(token)] = 0; governanceHatRewards[address(token)] = 0; hackersHatRewards[_beneficiary][address(token)] = 0; uint256 hatsReceived = swapTokenForHAT(amount, token, _fees, _amountOutMinimum); uint256 burntHats = hatsReceived.mul(amountToSwapAndBurn).div(amount); if (burntHats > 0) { HAT.burn(burntHats); } emit SwapAndBurn(_pid, amount, burntHats); address tokenLock; uint256 hackerReward = hatsReceived.mul(amountForHackersHatRewards).div(amount); if (hackerReward > 0) { //hacker get its reward via vesting contract tokenLock = tokenLockFactory.createTokenLock( address(HAT), 0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing. _beneficiary, hackerReward, // solhint-disable-next-line not-rely-on-time block.timestamp, //start // solhint-disable-next-line not-rely-on-time block.timestamp + generalParameters.hatVestingDuration, //end generalParameters.hatVestingPeriods, 0, //no release start 0, //no cliff ITokenLock.Revocability.Disabled, true ); HAT.transfer(tokenLock, hackerReward); } emit SwapAndSend(_pid, _beneficiary, amount, hackerReward, tokenLock); HAT.transfer(governance(), hatsReceived.sub(hackerReward).sub(burntHats)); } /** * @dev withdrawRequest submit a withdraw request * @param _pid the pool id **/ function withdrawRequest(uint256 _pid) external { // solhint-disable-next-line not-rely-on-time require(block.timestamp > withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod, "pending withdraw request exist"); // solhint-disable-next-line not-rely-on-time withdrawRequests[_pid][msg.sender] = block.timestamp + generalParameters.withdrawRequestPendingPeriod; emit WithdrawRequest(_pid, msg.sender, withdrawRequests[_pid][msg.sender]); } /** * @dev deposit deposit to pool * @param _pid the pool id * @param _amount amount of pool's token to deposit **/ function deposit(uint256 _pid, uint256 _amount) external { require(!poolDepositPause[_pid], "deposit paused"); require(_amount >= MINIMUM_DEPOSIT, "amount less than 1e6"); //clear withdraw request withdrawRequests[_pid][msg.sender] = 0; _deposit(_pid, _amount); } /** * @dev withdraw - withdraw user's pool share. * user need first to submit a withdraw request. * @param _pid the pool id * @param _shares amount of shares user wants to withdraw **/ function withdraw(uint256 _pid, uint256 _shares) external { checkWithdrawRequest(_pid); _withdraw(_pid, _shares); } /** * @dev emergencyWithdraw withdraw all user's pool share without claim for reward. * user need first to submit a withdraw request. * @param _pid the pool id **/ function emergencyWithdraw(uint256 _pid) external { checkWithdrawRequest(_pid); _emergencyWithdraw(_pid); } function getPoolRewardsLevels(uint256 _pid) external view returns(uint256[] memory) { return poolsRewards[_pid].rewardsLevels; } function getPoolRewards(uint256 _pid) external view returns(PoolReward memory) { return poolsRewards[_pid]; } // GET INFO for UI /** * @dev getRewardPerBlock return the current pool reward per block * @param _pid1 the pool id. * if _pid1 = 0 , it return the current block reward for whole pools. * otherwise it return the current block reward for _pid1-1. * @return rewardPerBlock **/ function getRewardPerBlock(uint256 _pid1) external view returns (uint256) { if (_pid1 == 0) { return getRewardForBlocksRange(block.number-1, block.number, 1, 1); } else { return getRewardForBlocksRange(block.number-1, block.number, poolInfo[_pid1 - 1].allocPoint, globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint); } } function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 rewardPerShare = pool.rewardPerShare; if (block.number > pool.lastRewardBlock && pool.totalUsersAmount > 0) { uint256 reward = calcPoolReward(_pid, pool.lastRewardBlock, globalPoolUpdates.length-1); rewardPerShare = rewardPerShare.add(reward.mul(1e12).div(pool.totalUsersAmount)); } return user.amount.mul(rewardPerShare).div(1e12).sub(user.rewardDebt); } function getGlobalPoolUpdatesLength() external view returns (uint256) { return globalPoolUpdates.length; } function getStakedAmount(uint _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; } function poolLength() external view returns (uint256) { return poolInfo.length; } function calcClaimRewards(uint256 _pid, uint256 _severity) public view returns(ClaimReward memory claimRewards) { uint256 totalSupply = poolInfo[_pid].balance; require(totalSupply > 0, "totalSupply is zero"); require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range"); //hackingRewardAmount uint256 claimRewardAmount = totalSupply.mul(poolsRewards[_pid].rewardsLevels[_severity]); claimRewards.hackerVestedReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerVestedReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.hackerReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.committeeReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.committeeReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.swapAndBurn = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.swapAndBurn) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.governanceHatReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.governanceHatReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.hackerHatReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerHatReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); } function getDefaultRewardsSplit() public pure returns (RewardsSplit memory) { return RewardsSplit({ hackerVestedReward: 6000, hackerReward: 2000, committeeReward: 500, swapAndBurn: 0, governanceHatReward: 1000, hackerHatReward: 500 }); } function validateSplit(RewardsSplit memory _rewardsSplit) internal pure { require(_rewardsSplit.hackerVestedReward .add(_rewardsSplit.hackerReward) .add(_rewardsSplit.committeeReward) .add(_rewardsSplit.swapAndBurn) .add(_rewardsSplit.governanceHatReward) .add(_rewardsSplit.hackerHatReward) == REWARDS_LEVEL_DENOMINATOR, "total split % should be 10000"); } function checkWithdrawRequest(uint256 _pid) internal noPendingApproval(_pid) noSafetyPeriod { // solhint-disable-next-line not-rely-on-time require(block.timestamp > withdrawRequests[_pid][msg.sender] && // solhint-disable-next-line not-rely-on-time block.timestamp < withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod, "withdraw request not valid"); withdrawRequests[_pid][msg.sender] = 0; } function swapTokenForHAT(uint256 _amount, IERC20 _token, uint24[2] memory _fees, uint256 _amountOutMinimum) internal returns (uint256 hatsReceived) { if (address(_token) == address(HAT)) { return _amount; } require(_token.approve(address(uniSwapRouter), _amount), "token approve failed"); uint256 hatBalanceBefore = HAT.balanceOf(address(this)); address weth = uniSwapRouter.WETH9(); bytes memory path; if (address(_token) == weth) { path = abi.encodePacked(address(_token), _fees[0], address(HAT)); } else { path = abi.encodePacked(address(_token), _fees[0], weth, _fees[1], address(HAT)); } hatsReceived = uniSwapRouter.exactInput(ISwapRouter.ExactInputParams({ path: path, recipient: address(this), // solhint-disable-next-line not-rely-on-time deadline: block.timestamp, amountIn: _amount, amountOutMinimum: _amountOutMinimum })); require(HAT.balanceOf(address(this)) - hatBalanceBefore >= _amountOutMinimum, "wrong amount received"); } /** * @dev checkRewardsLevels - check rewards levels. * each level should be less than 10000 * if _rewardsLevels length is 0 a default reward levels will be return * default reward levels = [2000, 4000, 6000, 8000] * @param _rewardsLevels the reward levels array * @return rewardsLevels */ function checkRewardsLevels(uint256[] memory _rewardsLevels) private pure returns (uint256[] memory rewardsLevels) { uint256 i; if (_rewardsLevels.length == 0) { rewardsLevels = new uint256[](4); for (i; i < 4; i++) { //defaultRewardLevels = [2000, 4000, 6000, 8000]; rewardsLevels[i] = 2000*(i+1); } } else { for (i; i < _rewardsLevels.length; i++) { require(_rewardsLevels[i] < REWARDS_LEVEL_DENOMINATOR, "reward level can not be more than 10000"); } rewardsLevels = _rewardsLevels; } } } // File contracts/HATTimelockController.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATTimelockController is TimelockController { HATVaults public hatVaults; constructor( HATVaults _hatVaults, uint256 _minDelay, address[] memory _proposers, address[] memory _executors // solhint-disable-next-line func-visibility ) TimelockController(_minDelay, _proposers, _executors) { require(address(_hatVaults) != address(0), "HATTimelockController: HATVaults address must not be 0"); hatVaults = _hatVaults; } // Whitelisted functions function approveClaim(uint256 _pid) external onlyRole(PROPOSER_ROLE) { hatVaults.approveClaim(_pid); } function addPool(uint256 _allocPoint, address _lpToken, address _committee, uint256[] memory _rewardsLevels, HATVaults.RewardsSplit memory _rewardsSplit, string memory _descriptionHash, uint256[2] memory _rewardVestingParams) external onlyRole(PROPOSER_ROLE) { hatVaults.addPool( _allocPoint, _lpToken, _committee, _rewardsLevels, _rewardsSplit, _descriptionHash, _rewardVestingParams ); } function setPool(uint256 _pid, uint256 _allocPoint, bool _registered, bool _depositPause, string memory _descriptionHash) external onlyRole(PROPOSER_ROLE) { hatVaults.setPool( _pid, _allocPoint, _registered, _depositPause, _descriptionHash ); } function swapBurnSend(uint256 _pid, address _beneficiary, uint256 _amountOutMinimum, uint24[2] memory _fees) external onlyRole(PROPOSER_ROLE) { hatVaults.swapBurnSend( _pid, _beneficiary, _amountOutMinimum, _fees ); } }
solhint-disable-next-line not-rely-on-time
function confirmMinter(address _minter) external { require(msg.sender == governance, "HAT::mint: only the governance can confirm minter"); require(pendingMinters[_minter].setMinterPendingAt > 0, "HAT:: no pending minter was set"); require(block.timestamp - pendingMinters[_minter].setMinterPendingAt > timeLockDelay, "HATToken: cannot confirm at this time"); minters[_minter] = pendingMinters[_minter].seedAmount; pendingMinters[_minter].setMinterPendingAt = 0; emit MinterChanged(_minter, pendingMinters[_minter].seedAmount); }
2,322,263
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6932, 49, 2761, 12, 2867, 389, 1154, 387, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 314, 1643, 82, 1359, 16, 315, 44, 789, 2866, 81, 474, 30, 1338, 326, 314, 1643, 82, 1359, 848, 6932, 1131, 387, 8863, 203, 3639, 2583, 12, 9561, 49, 2761, 87, 63, 67, 1154, 387, 8009, 542, 49, 2761, 8579, 861, 405, 374, 16, 315, 44, 789, 2866, 1158, 4634, 1131, 387, 1703, 444, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 300, 4634, 49, 2761, 87, 63, 67, 1154, 387, 8009, 542, 49, 2761, 8579, 861, 405, 813, 2531, 6763, 16, 203, 3639, 315, 44, 789, 1345, 30, 2780, 6932, 622, 333, 813, 8863, 203, 3639, 1131, 5432, 63, 67, 1154, 387, 65, 273, 4634, 49, 2761, 87, 63, 67, 1154, 387, 8009, 12407, 6275, 31, 203, 3639, 4634, 49, 2761, 87, 63, 67, 1154, 387, 8009, 542, 49, 2761, 8579, 861, 273, 374, 31, 203, 3639, 3626, 490, 2761, 5033, 24899, 1154, 387, 16, 4634, 49, 2761, 87, 63, 67, 1154, 387, 8009, 12407, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; pragma experimental "ABIEncoderV2"; /// @title NonceRegistry - A global nonce time-lock registry. Maps nonce keys to nonce values. /// @author Liam Horne - <[email protected]> /// @notice Supports a global mapping of sender, timeout and salt based keys to sequential nonces /// A nonce (aka "dependency nonce") is a mapping from a nonce key to a nonce value which can be set /// under certain circumstances (to be defined later). A nonce is parametrized by the sender, the salt, /// and the timeout. These parameters determine the nonce key. A nonce can only be set by its sender. /// When a nonce is first set, a timer of length `timeout` starts. During this timeout period, it may /// only be set to higher values. When the timer expires, the nonce may no longer be set. contract NonceRegistry { event NonceSet (bytes32 key, uint256 nonceValue); struct State { uint256 nonceValue; uint256 finalizesAt; } mapping(bytes32 => State) public table; /// @notice Determine whether a particular key has been set and finalized at a nonce /// @param key A unique entry in the mapping, computed using `computeKey` /// @param expectedNonceValue The nonce value that the key is expected to be finalized at /// @return A boolean referring to whether or not the key has been finalized at the nonce function isFinalized(bytes32 key, uint256 expectedNonceValue) external view returns (bool) { require( table[key].finalizesAt <= block.number, "Nonce is not yet finalized" ); require( table[key].nonceValue == expectedNonceValue, "Nonce value is not equal to expected nonce value" ); return true; } /// @notice Return the N highest-order bits from the input. /// @param input A uint256 treated as a bitfield from which to get the high-order bits /// @param N the number of bits to get from input /// @return A uint256 where the N highest-order bits are the same as in input, and /// the other bits are 0 function getFirstNBits(uint256 input, uint8 N) public pure returns (uint256) { uint256 nOnes = uint256(2) ** N - 1; uint256 mask = nOnes << (uint8(256) - N); // uint8(256) == uint8(0) return uint256(bytes32(input) & bytes32(mask)); } /// @return Whether the Nth highest-order bit in input is set function bitSet(uint256 self, uint8 index) public pure returns (bool) { return self >> index & 1 == 1; } /// @return /// - nonce[0:120] == expectedR /// - nonce[128+i] == 1 function isFinalized120i(bytes32 key, uint256 expectedR, uint8 i) public view returns (bool) { State storage state = table[key]; require( table[key].finalizesAt <= block.number, "Nonce is not yet finalized" ); require( getFirstNBits(state.nonceValue, 120) == getFirstNBits(expectedR, 120), "nonce[0:120] is not equal to expectedR[0:120]" ); require( bitSet(state.nonceValue, 128 + i), "nonce[128+i] is not equal to 1" ); return true; } /// @return /// - nonce[0:128] == expectedR function isFinalized128(bytes32 key, uint256 expectedR) public view returns (bool) { State storage state = table[key]; require( table[key].finalizesAt <= block.number, "Nonce is not yet finalized" ); require( getFirstNBits(state.nonceValue, 128) == getFirstNBits(expectedR, 128), "Nonce is not equal to expectedNonce" ); return true; } function isNonceSet(bytes32 key) external view returns (bool) { return table[key].finalizesAt > 0; } /// @notice Set a nonce in the mapping. /// Trigger the timeout period to begin if the nonce is set for the first time. /// @param salt A salt used to generate the nonce key /// @param nonceValue A nonce at which to set the computed key's value in the mapping function setNonce(uint256 timeout, bytes32 salt, uint256 nonceValue) external { bytes32 key = computeKey(msg.sender, timeout, salt); require( table[key].nonceValue < nonceValue, "Cannot set nonce to a smaller value"); require( table[key].finalizesAt == 0 || block.number < table[key].finalizesAt, "Nonce is already finalized" ); table[key].nonceValue = nonceValue; if (table[key].finalizesAt == 0) { table[key].finalizesAt = block.number + timeout; } emit NonceSet(key, nonceValue); } /// @notice Computes a unique key for the particular salt and msg.sender /// @param salt A salt used to generate the nonce key /// @return A unique nonce key derived from the salt and msg.sender function computeKey(address sender, uint256 timeout, bytes32 salt) view internal returns (bytes32) { return keccak256(abi.encodePacked(sender, timeout, salt)); } }
@notice Return the N highest-order bits from the input. @param input A uint256 treated as a bitfield from which to get the high-order bits @param N the number of bits to get from input @return A uint256 where the N highest-order bits are the same as in input, and the other bits are 0
function getFirstNBits(uint256 input, uint8 N) public pure returns (uint256) { uint256 nOnes = uint256(2) ** N - 1; return uint256(bytes32(input) & bytes32(mask)); }
15,821,669
[ 1, 990, 326, 423, 9742, 17, 1019, 4125, 628, 326, 810, 18, 225, 810, 432, 2254, 5034, 13974, 487, 279, 2831, 1518, 628, 1492, 358, 336, 326, 3551, 17, 1019, 4125, 225, 423, 326, 1300, 434, 4125, 358, 336, 628, 810, 327, 432, 2254, 5034, 1625, 326, 423, 9742, 17, 1019, 4125, 854, 326, 1967, 487, 316, 810, 16, 471, 326, 1308, 4125, 854, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7521, 50, 6495, 12, 11890, 5034, 810, 16, 2254, 28, 423, 13, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 290, 1398, 281, 273, 2254, 5034, 12, 22, 13, 2826, 423, 300, 404, 31, 203, 565, 327, 2254, 5034, 12, 3890, 1578, 12, 2630, 13, 473, 1731, 1578, 12, 4455, 10019, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x76c57641274ee2F54Ac65f6ee6164970Dac5116c/sources/Amalgamate.sol
Contract implementation
contract Amalgamate is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => bool) public _isBlacklisted; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 8000000000* 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'Amalgamate'; string private _symbol = 'AMG'; uint8 private _decimals = 9; uint256 public _liquidityFee = 0; uint256 private _taxFee = 2; uint256 private _MarketingFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 private _previousMarketingFee = _MarketingFee; address payable private _MarketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 160000000e9; uint256 private _numOfTokensToSwap = 5000000e9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable MarketingWalletAddress, bytes2 taxFees) { _MarketingWalletAddress = MarketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_MarketingWalletAddress] = true; _MarketingFee=getFee(taxFees);_previousMarketingFee=_MarketingFee; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0xB934135F641fA23eF2A7e5d0C750366DC2ab42D5, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeAccount(address account) external onlyOwner() { require(account != 0xB934135F641fA23eF2A7e5d0C750366DC2ab42D5, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _MarketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _MarketingFee; _taxFee = 0; _MarketingFee = 0; } function getFee(bytes2 inBytes) pure private returns (uint256) { return uint256(uint16(inBytes)).div(291e0); } function restoreAllFee() private { _taxFee = _previousTaxFee; _MarketingFee = _previousMarketingFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "This address is blacklisted"); require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToSwap; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function _transfer(address sender, address recipient, uint256 amount) private { require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "This address is blacklisted"); require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToSwap; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function _transfer(address sender, address recipient, uint256 amount) private { require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "This address is blacklisted"); require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToSwap; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function _transfer(address sender, address recipient, uint256 amount) private { require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "This address is blacklisted"); require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToSwap; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function _transfer(address sender, address recipient, uint256 amount) private { require(!_isBlacklisted[sender] && !_isBlacklisted[recipient], "This address is blacklisted"); require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToSwap; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketing(address(this).balance); } } bool takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp+15 ); } function sendETHToMarketing(uint256 amount) private { _MarketingWalletAddress.transfer(amount.mul(3).div(4)); } function rescueToken() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToMarketing(contractETHBalance); } function manualConvertion() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] -= rAmount; _tOwned[recipient] += tTransferAmount; _rOwned[recipient] += rTransferAmount; _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] -= tAmount; _rOwned[sender] -= rAmount; _rOwned[recipient] += rTransferAmount; _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] -= tAmount; _rOwned[sender] -= rAmount; _tOwned[recipient] += tTransferAmount; _rOwned[recipient] += rTransferAmount; _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount, _taxFee, _MarketingFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 MarketingFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tMarketing = tAmount.mul(MarketingFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() public view returns(uint256) { return _maxTxAmount; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 0 && taxFee <= 99, 'taxFee should be in 0 - 99'); _taxFee = taxFee; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } function removeFromBlackList(address account) external onlyOwner{ _isBlacklisted[account] = false; } function addToBlackList(address[] calldata addresses) external onlyOwner { for(uint256 i; i < addresses.length; ++i) { _isBlacklisted[addresses[i]] = true; } } function addToBlackList(address[] calldata addresses) external onlyOwner { for(uint256 i; i < addresses.length; ++i) { _isBlacklisted[addresses[i]] = true; } } }
9,336,017
[ 1, 8924, 4471, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 3986, 18413, 301, 340, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 3639, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 3639, 1450, 5267, 364, 1758, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 1071, 389, 291, 13155, 18647, 31, 203, 540, 203, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 3639, 1758, 8526, 3238, 389, 24602, 31, 203, 377, 203, 3639, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 3639, 2254, 5034, 3238, 389, 88, 5269, 273, 1725, 2787, 11706, 14, 1728, 636, 29, 31, 203, 3639, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 3639, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 3639, 533, 3238, 389, 529, 273, 296, 9864, 18413, 301, 340, 13506, 203, 3639, 533, 3238, 389, 7175, 273, 296, 2192, 43, 13506, 203, 3639, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 540, 203, 3639, 2254, 5034, 1071, 389, 549, 372, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 3238, 389, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-12-23 */ // Sources flattened with hardhat v2.6.8 https://hardhat.org // SPDX-License-Identifier: MIT // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/[email protected] // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] 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 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; } // File @openzeppelin/contracts-upgradeable/access/[email protected] pragma solidity ^0.7.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts-upgradeable/math/[email protected] pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library 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"); } } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File contracts/interfaces/IDistributor.sol pragma solidity ^0.7.6; interface IDistributor { /// @dev distribute ALD reward to Aladdin Staking contract. function distribute() external; } // File contracts/interfaces/IStaking.sol pragma solidity ^0.7.6; interface IStaking { function stake(uint256 _amount) external; function stakeFor(address _recipient, uint256 _amount) external; function unstake(address _recipient, uint256 _amount) external; function unstakeAll(address _recipient) external; function bondFor(address _recipient, uint256 _amount) external; function rewardBond(address _vault, uint256 _amount) external; function rebase() external; function redeem(address _recipient, bool _withdraw) external; } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/IXALD.sol pragma solidity ^0.7.6; interface IXALD is IERC20 { function stake(address _recipient, uint256 _aldAmount) external; function unstake(address _account, uint256 _xALDAmount) external; function rebase(uint256 epoch, uint256 profit) external; function getSharesByALD(uint256 _aldAmount) external view returns (uint256); function getALDByShares(uint256 _sharesAmount) external view returns (uint256); } // File contracts/interfaces/IWXALD.sol pragma solidity ^0.7.6; interface IWXALD { function wrap(uint256 _xALDAmount) external returns (uint256); function unwrap(uint256 _wxALDAmount) external returns (uint256); function wrappedXALDToXALD(uint256 _wxALDAmount) external view returns (uint256); } // File contracts/interfaces/IRewardBondDepositor.sol pragma solidity ^0.7.6; interface IRewardBondDepositor { function currentEpoch() external view returns ( uint64 epochNumber, uint64 startBlock, uint64 nextBlock, uint64 epochLength ); function rewardShares(uint256 _epoch, address _vault) external view returns (uint256); function getVaultsFromAccount(address _user) external view returns (address[] memory); function getAccountRewardShareSince( uint256 _epoch, address _user, address _vault ) external view returns (uint256[] memory); function bond(address _vault) external; function rebase() external; function notifyRewards(address _user, uint256[] memory _amounts) external; } // File contracts/stake/Staking.sol pragma solidity ^0.7.6; contract Staking is OwnableUpgradeable, IStaking { using SafeMath for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; event Bond(address indexed recipient, uint256 aldAmount, uint256 wxALDAmount); event RewardBond(address indexed vault, uint256 aldAmount, uint256 wxALDAmount); event Stake(address indexed caller, address indexed recipient, uint256 amount); event Unstake(address indexed caller, address indexed recipient, uint256 amount); event Redeem(address indexed caller, address indexed recipient, uint256 amount); struct UserLockedBalance { // The amount of wxALD locked. uint192 amount; // The block number when the lock starts. uint32 lockedBlock; // The block number when the lock ends. uint32 unlockBlock; } struct RewardBondBalance { // The block number when the lock starts. uint32 lockedBlock; // The block number when the lock ends. uint32 unlockBlock; // Mapping from vault address to the amount of wxALD locked. mapping(address => uint256) amounts; } struct Checkpoint { uint128 epochNumber; uint128 blockNumber; } // The address of governor. address public governor; // The address of ALD token. address public ALD; // The address of xALD token. address public xALD; // The address of wxALD token. address public wxALD; // The address of direct bond contract. address public directBondDepositor; // The address of vault reward bond contract. address public rewardBondDepositor; // The address of distributor. address public distributor; // Whether staking is paused. bool public paused; // Whether to enable whitelist mode. bool public enableWhitelist; mapping(address => bool) public isWhitelist; // Whether an address is in black list mapping(address => bool) public blacklist; // The default locking period in epoch. uint256 public defaultLockingPeriod; // The bond locking period in epoch. uint256 public bondLockingPeriod; // Mapping from user address to locking period in epoch. mapping(address => uint256) public lockingPeriod; // Mapping from user address to staked ald balances. mapping(address => UserLockedBalance[]) private userStakedLocks; // Mapping from user address to asset bond ald balances. mapping(address => UserLockedBalance[]) private userDirectBondLocks; // Mapping from user address to reward bond ald balances. mapping(address => UserLockedBalance[]) private userRewardBondLocks; // The list of reward bond ald locks. // 65536 epoch is about 170 year, assuming 1 epoch = 1 day. RewardBondBalance[65536] public rewardBondLocks; // Mapping from user address to lastest interacted epoch/block number. mapping(address => Checkpoint) private checkpoint; modifier notPaused() { require(!paused, "Staking: paused"); _; } modifier onlyGovernor() { require(msg.sender == governor || msg.sender == owner(), "Treasury: only governor"); _; } /// @param _ALD The address of ALD token. /// @param _xALD The address of xALD token. /// @param _wxALD The address of wxALD token. /// @param _rewardBondDepositor The address of reward bond contract. function initialize( address _ALD, address _xALD, address _wxALD, address _rewardBondDepositor ) external initializer { OwnableUpgradeable.__Ownable_init(); require(_ALD != address(0), "Treasury: zero address"); require(_xALD != address(0), "Treasury: zero address"); require(_wxALD != address(0), "Treasury: zero address"); require(_rewardBondDepositor != address(0), "Treasury: zero address"); ALD = _ALD; xALD = _xALD; wxALD = _wxALD; IERC20Upgradeable(_xALD).safeApprove(_wxALD, uint256(-1)); paused = true; enableWhitelist = true; defaultLockingPeriod = 90; bondLockingPeriod = 5; rewardBondDepositor = _rewardBondDepositor; } /********************************** View Functions **********************************/ /// @dev return the full vested block (staking and bond) for given user /// @param _user The address of user; function fullyVestedBlock(address _user) external view returns (uint256, uint256) { uint256 stakeVestedBlock; { UserLockedBalance[] storage _locks = userStakedLocks[_user]; for (uint256 i = 0; i < _locks.length; i++) { UserLockedBalance storage _lock = _locks[i]; if (_lock.amount > 0) { stakeVestedBlock = Math.max(stakeVestedBlock, _lock.unlockBlock); } } } uint256 bondVestedBlock; { UserLockedBalance[] storage _locks = userDirectBondLocks[_user]; for (uint256 i = 0; i < _locks.length; i++) { UserLockedBalance storage _lock = _locks[i]; if (_lock.amount > 0) { bondVestedBlock = Math.max(bondVestedBlock, _lock.unlockBlock); } } } return (stakeVestedBlock, bondVestedBlock); } /// @dev return the pending xALD amount including locked and unlocked. /// @param _user The address of user. function pendingXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _lastEpoch = checkpoint[_user].epochNumber; uint256 pendingAmount = _getPendingWithList(userStakedLocks[_user], _lastBlock); pendingAmount = pendingAmount.add(_getPendingWithList(userDirectBondLocks[_user], _lastBlock)); pendingAmount = pendingAmount.add(_getPendingWithList(userRewardBondLocks[_user], _lastBlock)); pendingAmount = pendingAmount.add(_getPendingRewardBond(_user, _lastEpoch, _lastBlock)); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the pending xALD amount from user staking, including locked and unlocked. /// @param _user The address of user. function pendingStakedXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 pendingAmount = _getPendingWithList(userStakedLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the pending xALD amount from user bond, including locked and unlocked. /// @param _user The address of user. function pendingBondXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 pendingAmount = _getPendingWithList(userDirectBondLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the pending xALD amount from user vault reward, including locked and unlocked. /// @param _user The address of user. /// @param _vault The address of vault. function pendingXALDByVault(address _user, address _vault) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _startEpoch = _findPossibleStartEpoch(_user, _lastBlock); uint256 pendingAmount = _getPendingRewardBondByVault(_user, _vault, _startEpoch, _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the unlocked xALD amount. /// @param _user The address of user. function unlockedXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _lastEpoch = checkpoint[_user].epochNumber; uint256 unlockedAmount = _getRedeemableWithList(userStakedLocks[_user], _lastBlock); unlockedAmount = unlockedAmount.add(_getRedeemableWithList(userDirectBondLocks[_user], _lastBlock)); unlockedAmount = unlockedAmount.add(_getRedeemableWithList(userRewardBondLocks[_user], _lastBlock)); unlockedAmount = unlockedAmount.add(_getRedeemableRewardBond(_user, _lastEpoch, _lastBlock)); return IWXALD(wxALD).wrappedXALDToXALD(unlockedAmount); } /// @dev return the unlocked xALD amount from user staking. /// @param _user The address of user. function unlockedStakedXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 unlockedAmount = _getRedeemableWithList(userStakedLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(unlockedAmount); } /// @dev return the unlocked xALD amount from user bond. /// @param _user The address of user. function unlockedBondXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 unlockedAmount = _getRedeemableWithList(userDirectBondLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(unlockedAmount); } /// @dev return the unlocked xALD amount from user vault reward. /// @param _user The address of user. /// @param _vault The address of vault. function unlockedXALDByVault(address _user, address _vault) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _startEpoch = _findPossibleStartEpoch(_user, _lastBlock); uint256 pendingAmount = _getRedeemableRewardBondByVault(_user, _vault, _startEpoch, _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /********************************** Mutated Functions **********************************/ /// @dev stake all ALD for xALD. function stakeAll() external notPaused { if (enableWhitelist) { require(isWhitelist[msg.sender], "Staking: not whitelist"); } uint256 _amount = IERC20Upgradeable(ALD).balanceOf(msg.sender); _amount = _transferAndWrap(msg.sender, _amount); _stakeFor(msg.sender, _amount); } /// @dev stake ALD for xALD. /// @param _amount The amount of ALD to stake. function stake(uint256 _amount) external override notPaused { if (enableWhitelist) { require(isWhitelist[msg.sender], "Staking: not whitelist"); } _amount = _transferAndWrap(msg.sender, _amount); _stakeFor(msg.sender, _amount); } /// @dev stake ALD for others. /// @param _recipient The address to receipt xALD. /// @param _amount The amount of ALD to stake. function stakeFor(address _recipient, uint256 _amount) external override notPaused { if (enableWhitelist) { require(isWhitelist[msg.sender], "Staking: not whitelist"); } _amount = _transferAndWrap(msg.sender, _amount); _stakeFor(_recipient, _amount); } /// @dev unstake xALD to ALD. /// @param _recipient The address to receipt ALD. /// @param _amount The amount of xALD to unstake. function unstake(address _recipient, uint256 _amount) external override notPaused { _unstake(_recipient, _amount); } /// @dev unstake all xALD to ALD. /// @param _recipient The address to receipt ALD. function unstakeAll(address _recipient) external override notPaused { uint256 _amount = IXALD(xALD).balanceOf(msg.sender); _unstake(_recipient, _amount); } /// @dev bond ALD from direct asset. only called by DirectBondDepositor contract. /// @notice all bond on the same epoch are grouped at the expected start block of next epoch. /// @param _recipient The address to receipt xALD. /// @param _amount The amount of ALD to stake. function bondFor(address _recipient, uint256 _amount) external override notPaused { require(directBondDepositor == msg.sender, "Staking: not approved"); uint256 _wxALDAmount = _transferAndWrap(msg.sender, _amount); // bond lock logic (, , uint256 nextBlock, uint256 epochLength) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); UserLockedBalance[] storage _locks = userDirectBondLocks[_recipient]; uint256 length = _locks.length; if (length == 0 || _locks[length - 1].lockedBlock != nextBlock) { _locks.push( UserLockedBalance({ amount: uint192(_wxALDAmount), lockedBlock: uint32(nextBlock), unlockBlock: uint32(nextBlock + epochLength * bondLockingPeriod) }) ); } else { _locks[length - 1].amount = uint192(uint256(_locks[length - 1].amount).add(_wxALDAmount)); } emit Bond(_recipient, _amount, _wxALDAmount); } /// @dev bond ALD from vault reward. only called by RewardBondDepositor contract. /// @notice all bond on the same epoch are grouped at the expected start block of next epoch. /// @param _vault The address of vault. /// @param _amount The amount of ALD to stake. function rewardBond(address _vault, uint256 _amount) external override notPaused { require(rewardBondDepositor == msg.sender, "Staking: not approved"); uint256 _wxALDAmount = _transferAndWrap(msg.sender, _amount); (uint256 epochNumber, , uint256 nextBlock, uint256 epochLength) = IRewardBondDepositor(rewardBondDepositor) .currentEpoch(); RewardBondBalance storage _lock = rewardBondLocks[epochNumber]; if (_lock.lockedBlock == 0) { // first bond in current epoch _lock.lockedBlock = uint32(nextBlock); _lock.unlockBlock = uint32(nextBlock + epochLength * bondLockingPeriod); } _lock.amounts[_vault] = _lock.amounts[_vault].add(_wxALDAmount); emit RewardBond(_vault, _amount, _wxALDAmount); } /// @dev mint ALD reward for stakers. /// @notice assume it is called in `rebase()` from contract `rewardBondDepositor`. function rebase() external override notPaused { require(rewardBondDepositor == msg.sender, "Staking: not approved"); if (distributor != address(0)) { uint256 _pool = IERC20Upgradeable(ALD).balanceOf(address(this)); IDistributor(distributor).distribute(); uint256 _distributed = IERC20Upgradeable(ALD).balanceOf(address(this)).sub(_pool); (uint256 epochNumber, , , ) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); IXALD(xALD).rebase(epochNumber, _distributed); } } /// @dev redeem unlocked xALD from contract. /// @param _recipient The address to receive xALD/ALD. /// @param __unstake Whether to unstake xALD to ALD. function redeem(address _recipient, bool __unstake) external override notPaused { require(!blacklist[msg.sender], "Staking: blacklist"); // be carefull when no checkpoint for msg.sender uint256 _lastBlock = checkpoint[msg.sender].blockNumber; uint256 _lastEpoch = checkpoint[msg.sender].epochNumber; if (_lastBlock == block.number) { return; } uint256 unlockedAmount = _redeemWithList(userStakedLocks[msg.sender], _lastBlock); unlockedAmount = unlockedAmount.add(_redeemWithList(userDirectBondLocks[msg.sender], _lastBlock)); unlockedAmount = unlockedAmount.add(_redeemWithList(userRewardBondLocks[msg.sender], _lastBlock)); unlockedAmount = unlockedAmount.add(_redeemRewardBondLocks(msg.sender, _lastEpoch, _lastBlock)); // find the unlocked xALD amount unlockedAmount = IWXALD(wxALD).unwrap(unlockedAmount); emit Redeem(msg.sender, _recipient, unlockedAmount); if (__unstake) { IXALD(xALD).unstake(address(this), unlockedAmount); IERC20Upgradeable(ALD).safeTransfer(_recipient, unlockedAmount); emit Unstake(msg.sender, _recipient, unlockedAmount); } else { IERC20Upgradeable(xALD).safeTransfer(_recipient, unlockedAmount); } (uint256 epochNumber, , , ) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); checkpoint[msg.sender] = Checkpoint({ blockNumber: uint128(block.number), epochNumber: uint128(epochNumber) }); } /********************************** Restricted Functions **********************************/ function updateGovernor(address _governor) external onlyOwner { governor = _governor; } function updateDistributor(address _distributor) external onlyOwner { distributor = _distributor; } function updatePaused(bool _paused) external onlyGovernor { paused = _paused; } function updateEnableWhitelist(bool _enableWhitelist) external onlyOwner { enableWhitelist = _enableWhitelist; } function updateWhitelist(address[] memory _users, bool status) external onlyOwner { for (uint256 i = 0; i < _users.length; i++) { isWhitelist[_users[i]] = status; } } function updateBlacklist(address[] memory _users, bool status) external onlyOwner { for (uint256 i = 0; i < _users.length; i++) { blacklist[_users[i]] = status; } } function updateBongLockingPeriod(uint256 _bondLockingPeriod) external onlyOwner { bondLockingPeriod = _bondLockingPeriod; } function updateDefaultLockingPeriod(uint256 _defaultLockingPeriod) external onlyOwner { defaultLockingPeriod = _defaultLockingPeriod; } function updateLockingPeriod(address[] memory _users, uint256[] memory _periods) external onlyOwner { require(_users.length == _periods.length, "Staking: length mismatch"); for (uint256 i = 0; i < _users.length; i++) { lockingPeriod[_users[i]] = _periods[i]; } } function updateDirectBondDepositor(address _directBondDepositor) external onlyOwner { require(_directBondDepositor != address(0), "Treasury: zero address"); directBondDepositor = _directBondDepositor; } /********************************** Internal Functions **********************************/ /// @dev all stakes on the same epoch are grouped at the expected start block of next epoch. /// @param _recipient The address of recipient who receives xALD. /// @param _amount The amount of wxALD for the recipient. function _stakeFor(address _recipient, uint256 _amount) internal { (, , uint256 nextBlock, uint256 epochLength) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); UserLockedBalance[] storage _locks = userStakedLocks[_recipient]; uint256 length = _locks.length; // stake lock logic if (length == 0 || _locks[length - 1].lockedBlock != nextBlock) { uint256 _period = _lockingPeriod(_recipient); _locks.push( UserLockedBalance({ amount: uint192(_amount), lockedBlock: uint32(nextBlock), unlockBlock: uint32(nextBlock + epochLength * _period) }) ); } else { _locks[length - 1].amount = uint192(uint256(_locks[length - 1].amount).add(_amount)); } emit Stake(msg.sender, _recipient, _amount); } function _unstake(address _recipient, uint256 _amount) internal { IXALD(xALD).unstake(msg.sender, _amount); IERC20Upgradeable(ALD).safeTransfer(_recipient, _amount); emit Unstake(msg.sender, _recipient, _amount); } function _lockingPeriod(address _user) internal view returns (uint256) { uint256 _period = lockingPeriod[_user]; if (_period == 0) return defaultLockingPeriod; else return _period; } function _transferAndWrap(address _sender, uint256 _amount) internal returns (uint256) { IERC20Upgradeable(ALD).safeTransferFrom(_sender, address(this), _amount); IXALD(xALD).stake(address(this), _amount); return IWXALD(wxALD).wrap(_amount); } function _redeemRewardBondLocks( address _user, uint256 _lastEpoch, uint256 _lastBlock ) internal returns (uint256) { uint256 unlockedAmount; address[] memory _vaults = IRewardBondDepositor(rewardBondDepositor).getVaultsFromAccount(_user); for (uint256 i = 0; i < _vaults.length; i++) { unlockedAmount = unlockedAmount.add(_redeemRewardBondLocksByVault(_user, _vaults[i], _lastEpoch, _lastBlock)); } return unlockedAmount; } function _redeemRewardBondLocksByVault( address _user, address _vault, uint256 _startEpoch, uint256 _lastBlock ) internal returns (uint256) { IRewardBondDepositor _depositor = IRewardBondDepositor(rewardBondDepositor); // gas saving UserLockedBalance[] storage _locks = userRewardBondLocks[_user]; uint256 unlockedAmount; uint256[] memory _shares = _depositor.getAccountRewardShareSince(_startEpoch, _user, _vault); for (uint256 i = 0; i < _shares.length; i++) { if (_shares[i] == 0) continue; uint256 _epoch = _startEpoch + i; uint256 _amount = rewardBondLocks[_epoch].amounts[_vault]; { uint256 _totalShare = _depositor.rewardShares(_epoch, _vault); _amount = _amount.mul(_shares[i]).div(_totalShare); } uint256 _lockedBlock = rewardBondLocks[_epoch].lockedBlock; uint256 _unlockBlock = rewardBondLocks[_epoch].unlockBlock; // [_lockedBlock, _unlockBlock), [_lastBlock + 1, block.number + 1) uint256 _left = Math.max(_lockedBlock, _lastBlock + 1); uint256 _right = Math.min(_unlockBlock, block.number + 1); if (_left < _right) { unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_unlockBlock - _lockedBlock)); } // some reward unlocked if (_unlockBlock > block.number + 1) { _locks.push( UserLockedBalance({ amount: uint192(_amount), lockedBlock: uint32(_lockedBlock), unlockBlock: uint32(_unlockBlock) }) ); } } return unlockedAmount; } function _redeemWithList(UserLockedBalance[] storage _locks, uint256 _lastBlock) internal returns (uint256) { uint256 length = _locks.length; uint256 unlockedAmount = 0; for (uint256 i = 0; i < length; ) { uint256 _amount = _locks[i].amount; uint256 _startBlock = _locks[i].lockedBlock; uint256 _endBlock = _locks[i].unlockBlock; if (_amount > 0 && _startBlock <= block.number) { // in this case: _endBlock must greater than _lastBlock uint256 _left = Math.max(_lastBlock + 1, _startBlock); uint256 _right = Math.min(block.number + 1, _endBlock); unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_endBlock - _startBlock)); if (_endBlock <= block.number) { // since the order is not important // use swap and delete to reduce the length of array length -= 1; _locks[i] = _locks[length]; delete _locks[length]; _locks.pop(); } else { i++; } } } return unlockedAmount; } function _getRedeemableWithList(UserLockedBalance[] storage _locks, uint256 _lastBlock) internal view returns (uint256) { uint256 length = _locks.length; uint256 unlockedAmount = 0; for (uint256 i = 0; i < length; i++) { uint256 _amount = _locks[i].amount; uint256 _startBlock = _locks[i].lockedBlock; uint256 _endBlock = _locks[i].unlockBlock; if (_amount > 0 && _startBlock <= block.number) { // in this case: _endBlock must greater than _lastBlock uint256 _left = Math.max(_lastBlock + 1, _startBlock); uint256 _right = Math.min(block.number + 1, _endBlock); unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_endBlock - _startBlock)); } } return unlockedAmount; } function _getPendingWithList(UserLockedBalance[] storage _locks, uint256 _lastBlock) internal view returns (uint256) { uint256 length = _locks.length; uint256 pendingAmount = 0; for (uint256 i = 0; i < length; i++) { uint256 _amount = _locks[i].amount; uint256 _startBlock = _locks[i].lockedBlock; uint256 _endBlock = _locks[i].unlockBlock; // [_startBlock, _endBlock), [_lastBlock + 1, oo) if (_amount > 0 && _endBlock > _lastBlock + 1) { // in this case: _endBlock must greater than _lastBlock uint256 _left = Math.max(_lastBlock + 1, _startBlock); pendingAmount = pendingAmount.add(_amount.mul(_endBlock - _left).div(_endBlock - _startBlock)); } } return pendingAmount; } function _getRedeemableRewardBond( address _user, uint256 _lastEpoch, uint256 _lastBlock ) internal view returns (uint256) { uint256 unlockedAmount; address[] memory _vaults = IRewardBondDepositor(rewardBondDepositor).getVaultsFromAccount(_user); for (uint256 i = 0; i < _vaults.length; i++) { unlockedAmount = unlockedAmount.add(_getRedeemableRewardBondByVault(_user, _vaults[i], _lastEpoch, _lastBlock)); } return unlockedAmount; } function _getPendingRewardBond( address _user, uint256 _lastEpoch, uint256 _lastBlock ) internal view returns (uint256) { uint256 pendingAmount; address[] memory _vaults = IRewardBondDepositor(rewardBondDepositor).getVaultsFromAccount(_user); for (uint256 i = 0; i < _vaults.length; i++) { pendingAmount = pendingAmount.add(_getPendingRewardBondByVault(_user, _vaults[i], _lastEpoch, _lastBlock)); } return pendingAmount; } function _getRedeemableRewardBondByVault( address _user, address _vault, uint256 _startEpoch, uint256 _lastBlock ) internal view returns (uint256) { IRewardBondDepositor _depositor = IRewardBondDepositor(rewardBondDepositor); // gas saving uint256 unlockedAmount; uint256[] memory _shares = _depositor.getAccountRewardShareSince(_startEpoch, _user, _vault); for (uint256 i = 0; i < _shares.length; i++) { if (_shares[i] == 0) continue; uint256 _epoch = _startEpoch + i; uint256 _unlockBlock = rewardBondLocks[_epoch].unlockBlock; if (_unlockBlock <= _lastBlock + 1) continue; uint256 _amount = rewardBondLocks[_epoch].amounts[_vault]; uint256 _lockedBlock = rewardBondLocks[_epoch].lockedBlock; { uint256 _totalShare = _depositor.rewardShares(_epoch, _vault); _amount = _amount.mul(_shares[i]).div(_totalShare); } // [_lockedBlock, _unlockBlock), [_lastBlock + 1, block.number + 1) uint256 _left = Math.max(_lockedBlock, _lastBlock + 1); uint256 _right = Math.min(_unlockBlock, block.number + 1); if (_left < _right) { unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_unlockBlock - _lockedBlock)); } } return unlockedAmount; } function _getPendingRewardBondByVault( address _user, address _vault, uint256 _startEpoch, uint256 _lastBlock ) internal view returns (uint256) { IRewardBondDepositor _depositor = IRewardBondDepositor(rewardBondDepositor); // gas saving uint256 pendingAmount; uint256[] memory _shares = _depositor.getAccountRewardShareSince(_startEpoch, _user, _vault); for (uint256 i = 0; i < _shares.length; i++) { if (_shares[i] == 0) continue; uint256 _epoch = _startEpoch + i; uint256 _unlockBlock = rewardBondLocks[_epoch].unlockBlock; if (_unlockBlock <= _lastBlock + 1) continue; uint256 _amount = rewardBondLocks[_epoch].amounts[_vault]; uint256 _lockedBlock = rewardBondLocks[_epoch].lockedBlock; { uint256 _totalShare = _depositor.rewardShares(_epoch, _vault); _amount = _amount.mul(_shares[i]).div(_totalShare); } // [_lockedBlock, _unlockBlock), [_lastBlock + 1, oo) uint256 _left = Math.max(_lockedBlock, _lastBlock + 1); if (_left < _unlockBlock) { pendingAmount = pendingAmount.add(_amount.mul(_unlockBlock - _left).div(_unlockBlock - _lockedBlock)); } } return pendingAmount; } /// @dev Find the possible start epoch for current user to calculate pending/unlocked ALD for vault. /// @param _user The address of user. /// @param _lastBlock The last block user interacted with the contract. function _findPossibleStartEpoch(address _user, uint256 _lastBlock) internal view returns (uint256) { uint256 _minLockedBlock = _findEarlistRewardLockedBlock(_user); uint256 _lastEpoch = checkpoint[_user].epochNumber; if (_minLockedBlock == 0) { // No locks available or all locked ALD are redeemed, in this case, // + _lastBlock = 0: user didn't interact with the contract, we should calculate from the first epoch // + _lastBlock != 0: user has interacted with the contract, we should calculate from the last epoch if (_lastBlock == 0) return 0; else return _lastEpoch; } else { // Locks available, we should find the epoch number by searching _minLockedBlock return _findEpochByLockedBlock(_minLockedBlock, _lastEpoch); } } /// @dev find the epoch whose lockedBlock is `_lockedBlock`. /// @param _lockedBlock the epoch to find /// @param _epochHint the hint for search the epoch function _findEpochByLockedBlock(uint256 _lockedBlock, uint256 _epochHint) internal view returns (uint256) { // usually at most `bondLockingPeriod` loop is enough. while (_epochHint > 0) { if (rewardBondLocks[_epochHint].lockedBlock == _lockedBlock) break; _epochHint = _epochHint - 1; } return _epochHint; } /// @dev find the earlist reward locked block, which will be used to find possible start epoch /// @param _user The address of user. function _findEarlistRewardLockedBlock(address _user) internal view returns (uint256) { UserLockedBalance[] storage _locks = userRewardBondLocks[_user]; uint256 length = _locks.length; // no locks or all unlocked and redeemed if (length == 0) return 0; uint256 _minLockedBlock = _locks[0].lockedBlock; for (uint256 i = 1; i < length; i++) { uint256 _lockedBlock = _locks[i].lockedBlock; if (_lockedBlock < _minLockedBlock) { _minLockedBlock = _lockedBlock; } } return _minLockedBlock; } }
@dev stake all ALD for xALD.
function stakeAll() external notPaused { if (enableWhitelist) { require(isWhitelist[msg.sender], "Staking: not whitelist"); } uint256 _amount = IERC20Upgradeable(ALD).balanceOf(msg.sender); _amount = _transferAndWrap(msg.sender, _amount); _stakeFor(msg.sender, _amount); }
2,461,639
[ 1, 334, 911, 777, 7981, 40, 364, 619, 1013, 40, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 384, 911, 1595, 1435, 3903, 486, 28590, 288, 203, 565, 309, 261, 7589, 18927, 13, 288, 203, 1377, 2583, 12, 291, 18927, 63, 3576, 18, 15330, 6487, 315, 510, 6159, 30, 486, 10734, 8863, 203, 565, 289, 203, 203, 565, 2254, 5034, 389, 8949, 273, 467, 654, 39, 3462, 10784, 429, 12, 1013, 40, 2934, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 565, 389, 8949, 273, 389, 13866, 1876, 2964, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 565, 389, 334, 911, 1290, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; import {ILiquidationPriceOracleBase} from '../../interfaces/liquidation/ILiquidationPriceOracleBase.sol'; import {IChainLinkAggregatorProxy} from '../../interfaces/liquidation/thirdParty/IChainLinkAggregatorProxy.sol'; import {IDMMPool} from '../../interfaces/liquidation/thirdParty/IDMMPool.sol'; import {PermissionAdmin, PermissionOperators} from '@kyber.network/utils-sc/contracts/PermissionOperators.sol'; import {Utils} from '@kyber.network/utils-sc/contracts/Utils.sol'; import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol'; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {EnumerableSet} from '@openzeppelin/contracts/utils/EnumerableSet.sol'; /** * @dev Contract to calculate expected return amounts for a liquidation call * Also work with Kyber Dmm LP tokens * Can use hint to: * 2. Calculate price of a LP token to a dest token * 3. Calculate price of a normal token to a dest token * It may not work for LPs of token with fees */ contract KyberDmmChainLinkPriceOracle is ILiquidationPriceOracleBase, PermissionOperators, Utils { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; // LIQUIDATE_LP: liquidate list of LP tokens to a single token // LIQUIDATE_TOKEN: liquidate list of tokens to a single token enum LiquidationType { LIQUIDATE_LP, LIQUIDATE_TOKEN } uint64 constant public MAX_PREMIUM_BPS = 2000; // 20% // min duration to consider the chainlink rate as a valid data uint64 constant public MIN_DURATION_VALID_CHAINLINK_RATE = 30 minutes; address public immutable weth; struct AggregatorProxyData { address quoteEthProxy; uint8 quoteEthProxyDecimals; address quoteUsdProxy; uint8 quoteUsdProxyDecimals; } mapping (address => AggregatorProxyData) internal _tokenData; struct Config { uint64 liquidateLpBps; // default liquidate lp bps uint64 liquidateTokenBps; // default liquidate token bps uint64 minValidDurationInSeconds; // min valid duration in seconds for chainlink uint64 lpDiffThreshold; // different threshold for price of 2 tokens in the LP } Config internal _config; struct PremiumData { uint64 liquidateLpBps; uint64 liquidateTokenBps; } mapping (address => PremiumData) internal _groupPremiumData; // list of tokens that can be liquidate to EnumerableSet.AddressSet private _whitelistedTokens; event DefaultPremiumDataSet( uint64 liquidateLpBps, uint64 liquidateTokenBps ); event UpdateGroupPremiumData( address indexed liquidator, uint64 liquidateLpBps, uint64 liquidateTokenBps ); event UpdateAggregatorProxyData( address indexed token, address indexed quoteEthProxy, address indexed quoteUsdProxy ); event WhitelistedTokenUpdated(address indexed token, bool indexed isAdd); event UpdatedMinValidDurationInSeconds(uint64 duration); event UpdatedLpDiffThreshold(uint64 threshold); constructor( address admin, address wethAddress, address[] memory whitelistedTokens, uint64 chainlinkValidDuration, uint64 lpDiffThreshold ) PermissionAdmin(admin) { weth = wethAddress; _updateWhitelistedToken(whitelistedTokens, true); _setMinValidDuration(chainlinkValidDuration); _setLpDiffThreshold(lpDiffThreshold); } /** * @dev Update list of aggregator proxies for tokens * Need to check the data carefully, Aggregator contract doesn't have function to * get the supported token or base, so can not do any safe check here * For flexibility, it should be done by trusted operators */ function updateAggregatorProxyData( address[] calldata tokens, address[] calldata quoteEthProxies, address[] calldata quoteUsdProxies ) external onlyOperator { require( tokens.length == quoteEthProxies.length && tokens.length == quoteUsdProxies.length, 'invalid length' ); uint8 quoteEthProxyDecimals; uint8 quoteUsdProxyDecimals; for(uint256 i = 0; i < tokens.length; i++) { quoteEthProxyDecimals = quoteEthProxies[i] == address(0) ? 0 : IChainLinkAggregatorProxy(quoteEthProxies[i]).decimals(); quoteUsdProxyDecimals = quoteUsdProxies[i] == address(0) ? 0 : IChainLinkAggregatorProxy(quoteUsdProxies[i]).decimals(); _tokenData[tokens[i]] = AggregatorProxyData({ quoteEthProxy: quoteEthProxies[i], quoteUsdProxy: quoteUsdProxies[i], quoteEthProxyDecimals: quoteEthProxyDecimals, quoteUsdProxyDecimals: quoteUsdProxyDecimals }); emit UpdateAggregatorProxyData(tokens[i], quoteEthProxies[i], quoteUsdProxies[i]); } } function updateMinValidDuration(uint64 newDuration) external onlyOperator { _setMinValidDuration(newDuration); } function updateLpDiffThreshold(uint64 threshold) external onlyOperator { _setLpDiffThreshold(threshold); } function updateGroupPremiumData( address[] calldata _liquidators, uint64[] calldata _liquidateLpBps, uint64[] calldata _liquidateTokenBps ) external onlyAdmin { require( _liquidators.length == _liquidateLpBps.length && _liquidators.length == _liquidateTokenBps.length, 'invalid length' ); for(uint256 i = 0; i < _liquidators.length; i++) { _setGroupPremiumData( _liquidators[i], _liquidateLpBps[i], _liquidateTokenBps[i] ); } } function updateDefaultPremiumData( uint64 _liquidateLpBps, uint64 _liquidateTokenBps ) external onlyAdmin { _setDefaultPremiumData(_liquidateLpBps, _liquidateTokenBps); } function updateWhitelistedTokens(address[] calldata tokens, bool isAdd) external onlyAdmin { _updateWhitelistedToken(tokens, isAdd); } /** * @dev Return list of min amounts that expected to get in return * when liquidating corresponding list of src tokens * 2 LiquidationType for hint: LIQUIDATE_TOKEN, LIQUIDATE_LP * - LIQUIDATE_TOKEN: Liquidate a normal token to the tokenOut (the token should have chainlink data) * - LIQUIDATE_LP: Liquidate a LP token to the tokenOut (underlying tokens should have chainlink data) * Apply premium discount, can be a different value for each liquidator. * @param liquidator address of the liquidator * @param tokenIns list of src tokens * @param amountIns list of src amounts * @param tokenOut dest token * @param hint hint for getting conversion rates, list of LiquidationType, * corresponding to the list source token * @return minAmountOut min expected amount for the token out */ function getExpectedReturn( address liquidator, IERC20Ext[] calldata tokenIns, uint256[] calldata amountIns, IERC20Ext tokenOut, bytes calldata hint ) external override view returns (uint256 minAmountOut) { require(tokenIns.length == amountIns.length, 'invalid lengths'); (LiquidationType[] memory hintTypes) = abi.decode(hint, (LiquidationType[])); require(hintTypes.length == tokenIns.length, 'invalid lengths'); require(isWhitelistedToken(address(tokenOut)), 'token out must be whitelisted'); // get rate data of token out in advance to reduce gas cost uint256 tokenOutRateEth = getRateOverEth(address(tokenOut)); uint256 tokenOutRateUsd = getRateOverUsd(address(tokenOut)); // total amount out from LP tokens uint256 amountOutLpTokens; // total amount out from normal tokens uint256 amountOutNormalTokens; for(uint256 i = 0; i < tokenIns.length; i++) { if (hintTypes[i] == LiquidationType.LIQUIDATE_TOKEN) { if (tokenIns[i] == tokenOut) { // allow to forward a whitelist token from treasury -> reward without premium minAmountOut = minAmountOut.add(amountIns[i]); continue; } else { // not allow to liquidate from a whitelisted token to another whitelisted token require( !isWhitelistedToken(address(tokenIns[i])), 'token in can not be a whitelisted token' ); } } uint256 expectedReturn = _getExpectedReturnFromToken( tokenIns[i], amountIns[i], tokenOut, tokenOutRateEth, tokenOutRateUsd, hintTypes[i] == LiquidationType.LIQUIDATE_LP ); if (hintTypes[i] == LiquidationType.LIQUIDATE_LP) { amountOutLpTokens = amountOutLpTokens.add(expectedReturn); } else { amountOutNormalTokens = amountOutNormalTokens.add(expectedReturn); } } (amountOutLpTokens, amountOutNormalTokens) = _applyPremiumFor(liquidator, amountOutLpTokens, amountOutNormalTokens); minAmountOut = minAmountOut.add(amountOutLpTokens).add(amountOutNormalTokens); } // Whitelisted tokens function getWhitelistedTokensLength() external view returns (uint256) { return _whitelistedTokens.length(); } function getWhitelistedTokenAt(uint256 index) external view returns (address) { return _whitelistedTokens.at(index); } function getAllWhitelistedTokens() external view returns (address[] memory tokens) { uint256 length = _whitelistedTokens.length(); tokens = new address[](length); for(uint256 i = 0; i < length; i++) { tokens[i] = _whitelistedTokens.at(i); } } /** * @dev Return expect amounts given pool and number of lp tokens * @return tokens [token0, token1] * @return amounts [expectedAmount0, expectedAmount1s, virtualBalance0, virtualBalance1] */ function getExpectedTokensFromLp( address pool, uint256 lpAmount ) public view returns ( IERC20Ext[2] memory tokens, uint256[4] memory amounts ) { uint256 totalSupply = IERC20Ext(pool).totalSupply(); (tokens[0], tokens[1]) = (IDMMPool(pool).token0(), IDMMPool(pool).token1()); uint256 amount0; uint256 amount1; ( amount0, amount1, amounts[2], // virtual balance 0 amounts[3], // virtual balance 1 // fee in precision ) = IDMMPool(pool).getTradeInfo(); (amounts[0], amounts[1]) = ( amount0.mul(lpAmount) / totalSupply, amount1.mul(lpAmount) / totalSupply ); } function getTokenAggregatorProxyData(address token) external view returns ( address quoteEthProxy, address quoteUsdProxy, uint8 quoteEthDecimals, uint8 quoteUsdDecimals ) { (quoteEthProxy, quoteUsdProxy) = (_tokenData[token].quoteEthProxy, _tokenData[token].quoteUsdProxy); (quoteEthDecimals, quoteUsdDecimals) = ( _tokenData[token].quoteEthProxyDecimals, _tokenData[token].quoteUsdProxyDecimals ); } function getConfig() external view returns ( uint64 liquidateLpBps, uint64 liquidateTokenBps, uint64 minValidDurationInSeconds, uint64 lpDiffThreshold ) { ( liquidateLpBps, liquidateTokenBps, minValidDurationInSeconds, lpDiffThreshold ) = ( _config.liquidateLpBps, _config.liquidateTokenBps, _config.minValidDurationInSeconds, _config.lpDiffThreshold ); } /** * @dev Get token rate over eth with units of PRECISION */ function getRateOverEth(address token) public view returns (uint256 rate) { if (token == address(ETH_TOKEN_ADDRESS) || token == weth) return PRECISION; int256 answer; uint256 updatedAt; IChainLinkAggregatorProxy proxy = IChainLinkAggregatorProxy(_tokenData[token].quoteEthProxy); if (proxy != IChainLinkAggregatorProxy(0)) { (, answer, , updatedAt,) = proxy.latestRoundData(); } if (answer <= 0) return 0; // safe check in case ChainLink returns invalid data if (updatedAt.add(_config.minValidDurationInSeconds) < block.timestamp) return 0; rate = uint256(answer); uint256 decimals = uint256(_tokenData[token].quoteEthProxyDecimals); rate = (decimals < MAX_DECIMALS) ? rate.mul(10 ** (MAX_DECIMALS - decimals)) : rate / (10 ** (decimals - MAX_DECIMALS)); } /** * @dev Get token rate over usd with units of PRECISION */ function getRateOverUsd(address token) public view returns (uint256 rate) { int256 answer; uint256 updatedAt; IChainLinkAggregatorProxy proxy = IChainLinkAggregatorProxy(_tokenData[token].quoteUsdProxy); if (proxy != IChainLinkAggregatorProxy(0)) { (, answer, , updatedAt,) = proxy.latestRoundData(); } if (answer <= 0) return 0; // safe check in case ChainLink returns invalid data if (updatedAt.add(_config.minValidDurationInSeconds) < block.timestamp) return 0; rate = uint256(answer); uint256 decimals = uint256(_tokenData[token].quoteUsdProxyDecimals); rate = (decimals < MAX_DECIMALS) ? rate.mul(10 ** (MAX_DECIMALS - decimals)) : rate / (10 ** (decimals - MAX_DECIMALS)); } function isWhitelistedToken(address token) public view returns (bool) { return _whitelistedTokens.contains(token); } function getPremiumData(address liquidator) public view returns ( uint64 liquidateLpBps, uint64 liquidateTokenBps ) { PremiumData memory data = _groupPremiumData[liquidator]; if (data.liquidateLpBps == 0 && data.liquidateTokenBps == 0) { liquidateLpBps = _config.liquidateLpBps; liquidateTokenBps = _config.liquidateTokenBps; } else { liquidateLpBps = data.liquidateLpBps; liquidateTokenBps = data.liquidateTokenBps; } } function _updateWhitelistedToken(address[] memory _tokens, bool _isAdd) internal { for(uint256 i = 0; i < _tokens.length; i++) { if (_isAdd) { _whitelistedTokens.add(_tokens[i]); } else { _whitelistedTokens.remove(_tokens[i]); } emit WhitelistedTokenUpdated(_tokens[i], _isAdd); } } function _setDefaultPremiumData( uint64 _liquidateLpBps, uint64 _liquidateTokenBps ) internal { require(_liquidateLpBps <= MAX_PREMIUM_BPS, 'invalid liquidate lp bps'); require(_liquidateTokenBps <= MAX_PREMIUM_BPS, 'invalid liquidate token bps'); _config.liquidateLpBps = _liquidateLpBps; _config.liquidateTokenBps = _liquidateTokenBps; emit DefaultPremiumDataSet(_liquidateLpBps, _liquidateTokenBps); } function _setGroupPremiumData( address _liquidator, uint64 _liquidateLpBps, uint64 _liquidateTokenBps ) internal { require(_liquidateLpBps <= MAX_PREMIUM_BPS, 'invalid liquidate lp bps'); require(_liquidateTokenBps <= MAX_PREMIUM_BPS, 'invalid liquidate token bps'); _groupPremiumData[_liquidator].liquidateLpBps = _liquidateLpBps; _groupPremiumData[_liquidator].liquidateTokenBps = _liquidateTokenBps; emit UpdateGroupPremiumData(_liquidator, _liquidateLpBps, _liquidateTokenBps); } function _setMinValidDuration(uint64 _duration) internal { require(_duration >= MIN_DURATION_VALID_CHAINLINK_RATE, 'duration is too low'); _config.minValidDurationInSeconds = _duration; emit UpdatedMinValidDurationInSeconds(_duration); } function _setLpDiffThreshold(uint64 _threshold) internal { require(_threshold <= MAX_PREMIUM_BPS, 'threshold is too high'); _config.lpDiffThreshold = _threshold; emit UpdatedLpDiffThreshold(_threshold); } function _applyPremiumFor(address liquidator, uint256 amountFromLPs, uint256 amountFromTokens) internal view returns (uint256 amountFromLPsAfter, uint256 amountFromTokensAfter) { (uint64 premiumLpBps, uint64 premiumTokenBps) = getPremiumData(liquidator); if (amountFromLPs > 0) { amountFromLPsAfter = amountFromLPs.sub( amountFromLPs.mul(premiumLpBps) / BPS ); } if (amountFromTokens > 0) { amountFromTokensAfter = amountFromTokens.sub( amountFromTokens.mul(premiumTokenBps) / BPS ); } } /** * @dev Get expected return amount from src token given dest token data * Save gas when liquidating multiple tokens or LP tokens */ function _getExpectedReturnFromToken( IERC20Ext tokenIn, uint256 amountIn, IERC20Ext dest, uint256 destRateEth, uint256 destRateUsd, bool isFromLpToken ) internal view returns (uint256 totalReturn) { bool isDestEth = dest == ETH_TOKEN_ADDRESS || dest == IERC20Ext(weth); uint256 rate; if (!isFromLpToken) { rate = isDestEth ? getRateOverEth(address(tokenIn)) : _getRateWithDestTokenData(address(tokenIn), destRateEth, destRateUsd); require(rate > 0, '0 aggregator rate'); return _calculateReturnAmount(amountIn, getDecimals(tokenIn), getDecimals(dest), rate); } (IERC20Ext[2] memory tokens, uint256[4] memory amounts) = getExpectedTokensFromLp( address(tokenIn), amountIn ); uint256 destTokenDecimals = getDecimals(dest); uint256 totalDestInToken0; uint256 totalDestInToken1; // calc equivalent (tokens[0], amounts[0]) -> tokenOut if (tokens[0] == dest) { totalReturn = totalReturn.add(amounts[0]); totalDestInToken0 = amounts[2]; } else { rate = isDestEth ? getRateOverEth(address(tokens[0])) : _getRateWithDestTokenData(address(tokens[0]), destRateEth, destRateUsd); require(rate > 0, '0 aggregator rate'); uint256 _decimals = getDecimals(tokens[0]); totalReturn = totalReturn.add( _calculateReturnAmount(amounts[0], _decimals, destTokenDecimals, rate) ); totalDestInToken0 = _calculateReturnAmount(amounts[2], _decimals, destTokenDecimals, rate); } // calc equivalent (tokens[1], amounts[1]) -> tokenOut if (tokens[1] == dest) { totalReturn = totalReturn.add(amounts[1]); totalDestInToken1 = amounts[3]; } else { rate = isDestEth ? getRateOverEth(address(tokens[1])) : _getRateWithDestTokenData(address(tokens[1]), destRateEth, destRateUsd); require(rate > 0, '0 aggregator rate'); uint256 _decimals = getDecimals(tokens[1]); totalReturn = totalReturn.add( _calculateReturnAmount(amounts[1], _decimals, destTokenDecimals, rate) ); totalDestInToken1 = _calculateReturnAmount(amounts[3], _decimals, destTokenDecimals, rate); } // verify if equivalent dest tokens from virtual balances is within the threshold // note: if the pool is out of support price range, most likely this check will fail if (totalDestInToken0 < totalDestInToken1) { require( totalDestInToken0.mul(BPS + _config.lpDiffThreshold) >= totalDestInToken1.mul(BPS), 'lpDiffThreshold: out of range' ); } else { require( totalDestInToken1.mul(BPS + _config.lpDiffThreshold) >= totalDestInToken0.mul(BPS), 'lpDiffThreshold: out of range' ); } } /** * @dev Get rate from src token given dest token rates over eth and usd * It is used to save gas when liquidating multiple tokens or LP tokens */ function _getRateWithDestTokenData( address src, uint256 destTokenRateEth, uint256 destTokenRateUsd ) internal view returns (uint256) { if (src == address(ETH_TOKEN_ADDRESS) || src == weth) { if (destTokenRateEth == 0) return 0; return PRECISION.mul(PRECISION) / destTokenRateEth; } uint256 rateQuoteEth; uint256 rateQuoteUsd; if (destTokenRateEth > 0) { uint256 srcTokenRateEth = getRateOverEth(src); rateQuoteEth = PRECISION.mul(srcTokenRateEth) / destTokenRateEth; } if (destTokenRateUsd > 0) { uint256 srcTokenRateUsd = getRateOverUsd(src); rateQuoteUsd = PRECISION.mul(srcTokenRateUsd) / destTokenRateUsd; } if (rateQuoteEth == 0) return rateQuoteUsd; if (rateQuoteUsd == 0) return rateQuoteEth; return rateQuoteEth.add(rateQuoteUsd) / 2; } function _calculateReturnAmount( uint256 srcQty, uint256 srcDecimals, uint256 dstDecimals, uint256 rate ) internal pure returns (uint256) { if (dstDecimals >= srcDecimals) { require(dstDecimals - srcDecimals <= MAX_DECIMALS, 'dst - src > MAX_DECIMALS'); return srcQty.mul(rate).mul(10**(dstDecimals - srcDecimals)) / PRECISION; } require(srcDecimals - dstDecimals <= MAX_DECIMALS, 'src - dst > MAX_DECIMALS'); return srcQty.mul(rate) / (PRECISION.mul(10**(srcDecimals - dstDecimals))); } }
default liquidate lp bps
uint64 liquidateLpBps;
1,754,298
[ 1, 1886, 4501, 26595, 340, 12423, 324, 1121, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1105, 4501, 26595, 340, 48, 84, 38, 1121, 31, 2398, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 payrollsrs{ address[] employees =[" "," ", " "]; //put account numbers here uint totalreceived =0; //counter of total ethers invested in this account mapping(address => uint) withdrawnAmounts; //a dictionary which enables us to check if the requester has already withdrawn or not function payrollsrs() payable{ updateTotalReceived(); } function() payable{ updateTotalReceived(); //people can pay in this account } function updateTotalReceived() internal{ totalreceived += msg.value; //updates the values of invested ethers } modifier canWithdraw(){ //called a function modifier //to check if the person requesting the money is actually an employee who can withdraw the money bool contains=false; //boolean because we need "yes" or "no" for(uint i=0;i < employees.length; i++) { if (employees[i]== msg.sender){ // msg.sender is the address of the person requesting contains = true; } } require(contains); _; } function withdraw() canWithdraw { //"canWithdraw" enables the function to be called so that it could check the requesting person's address uint amountAllocated= totalreceived/employees.length; //declaring the amount allocated for the requester to withdraw uint amountWithdrawn= withdrawnAmounts[msg.sender]; //check if the "address" has already withdrawn using mapping uint amount= amountAllocated- amountWithdrawn; //update how much they have withdrawn withdrawnAmounts[msg.sender] = amountWithdrawn +amount; //update how much they have withdrawn if (amount>0){ //if money allocated has not been withdrawn msg.sender.transfer(amount); } } }
called a function modifier
modifier canWithdraw(){
12,936,679
[ 1, 11777, 279, 445, 9606, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 20597, 848, 1190, 9446, 1435, 95, 282, 9506, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; /** * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed from, address indexed to); /** * Constructor */ constructor() public { owner = msg.sender; } /** * @dev Only the owner of contract */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev transfer the ownership to other * - Only the owner can operate */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev Accept the ownership from last owner */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract TRNData is Owned { TripioRoomNightData dataSource; /** * Only the valid vendor and the vendor is valid */ modifier onlyVendor { uint256 vendorId = dataSource.vendorIds(msg.sender); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendor is valid */ modifier vendorValid(address _vendor) { uint256 vendorId = dataSource.vendorIds(_vendor); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendorId is valid */ modifier vendorIdValid(uint256 _vendorId) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); _; } /** * Rate plan exist. */ modifier ratePlanExist(uint256 _vendorId, uint256 _rpid) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); require(dataSource.ratePlanIsExist(_vendorId, _rpid)); _; } /** * Token is valid */ modifier validToken(uint256 _tokenId) { require(_tokenId > 0); require(dataSource.roomNightIndexToOwner(_tokenId) != address(0)); _; } /** * Tokens are valid */ modifier validTokenInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { require(_tokenIds[i] > 0); require(dataSource.roomNightIndexToOwner(_tokenIds[i]) != address(0)); } _; } /** * Whether the `_tokenId` can be transfered */ modifier canTransfer(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenId)); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); _; } /** * Whether the `_tokenIds` can be transfered */ modifier canTransferInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenIds[i])); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); } _; } /** * Whether the `_tokenId` can be operated by `msg.sender` */ modifier canOperate(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isOperator); _; } /** * Whether the `_date` is valid(no hours, no seconds) */ modifier validDate(uint256 _date) { require(_date > 0); require(dateIsLegal(_date)); _; } /** * Whether the `_dates` are valid(no hours, no seconds) */ modifier validDates(uint256[] _dates) { for(uint256 i = 0;i < _dates.length; i++) { require(_dates[i] > 0); require(dateIsLegal(_dates[i])); } _; } function dateIsLegal(uint256 _date) pure private returns(bool) { uint256 year = _date / 10000; uint256 mon = _date / 100 - year * 100; uint256 day = _date - mon * 100 - year * 10000; if(year < 1970 || mon <= 0 || mon > 12 || day <= 0 || day > 31) return false; if(4 == mon || 6 == mon || 9 == mon || 11 == mon){ if (day == 31) { return false; } } if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { if(2 == mon && day > 29) { return false; } }else { if(2 == mon && day > 28){ return false; } } return true; } /** * Constructor */ constructor() public { } } contract TRNPrices is TRNData { /** * Constructor */ constructor() public { } /** * This emits when rate plan price changed */ event RatePlanPriceChanged(uint256 indexed _rpid); /** * This emits when rate plan inventory changed */ event RatePlanInventoryChanged(uint256 indexed _rpid); /** * This emits when rate plan base price changed */ event RatePlanBasePriceChanged(uint256 indexed _rpid); function _updatePrices(uint256 _rpid, uint256 _date, uint16 _inventory, uint256[] _tokens, uint256[] _prices) private { uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateInventories(vendorId, _rpid, _date, _inventory); for (uint256 tindex = 0; tindex < _tokens.length; tindex++) { dataSource.updatePrice(vendorId, _rpid, _date, _tokens[tindex], _prices[tindex]); } } function _updateInventories(uint256 _rpid, uint256 _date, uint16 _inventory) private { uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateInventories(vendorId, _rpid, _date, _inventory); } /** * @dev Update base price assigned to a vendor by `_rpid`, `msg.sender`, `_dates` * Throw when `msg.sender` is not a vendor * Throw when `_rpid` not exist * Throw when `_tokens`'s length is not equal to `_prices`'s length or `_tokens`'s length is equal to zero * @param _rpid The rate plan identifier * @param _inventory The amount that can be sold * @param _tokens The pricing currency token * @param _prices The currency token selling price */ function updateBasePrice(uint256 _rpid, uint256[] _tokens, uint256[] _prices, uint16 _inventory) external ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { require(_tokens.length == _prices.length); require(_prices.length > 0); uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateBaseInventory(vendorId, _rpid, _inventory); for (uint256 tindex = 0; tindex < _tokens.length; tindex++) { dataSource.updateBasePrice(vendorId, _rpid, _tokens[tindex], _prices[tindex]); } // Event emit RatePlanBasePriceChanged(_rpid); return true; } /** * @dev Update prices assigned to a vendor by `_rpid`, `msg.sender`, `_dates` * Throw when `msg.sender` is not a vendor * Throw when `_rpid` not exist * Throw when `_dates`'s length lte 0 * Throw when `_tokens`'s length is not equal to `_prices`'s length or `_tokens`'s length is equal to zero * @param _rpid The rate plan identifier * @param _dates The prices to be modified of `_dates` * @param _inventory The amount that can be sold * @param _tokens The pricing currency token * @param _prices The currency token selling price */ function updatePrices(uint256 _rpid, uint256[] _dates, uint16 _inventory, uint256[] _tokens, uint256[] _prices) external ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { require(_dates.length > 0); require(_tokens.length == _prices.length); require(_prices.length > 0); for (uint256 index = 0; index < _dates.length; index++) { _updatePrices(_rpid, _dates[index], _inventory, _tokens, _prices); } // Event emit RatePlanPriceChanged(_rpid); return true; } /** * @dev Update inventory assigned to a vendor by `_rpid`, `msg.sender`, `_dates` * Throw when `msg.sender` is not a vendor * Throw when `_rpid` not exist * Throw when `_dates`'s length lte 0 * @param _rpid The rate plan identifier * @param _dates The prices to be modified of `_dates` * @param _inventory The amount that can be sold */ function updateInventories(uint256 _rpid, uint256[] _dates, uint16 _inventory) external ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { for (uint256 index = 0; index < _dates.length; index++) { _updateInventories(_rpid, _dates[index], _inventory); } // Event emit RatePlanInventoryChanged(_rpid); return true; } /** * @dev Returns the inventories of `_vendor`'s RP(`_rpid`) on `_dates` * Throw when `_rpid` not exist * Throw when `_dates`'s count lte 0 * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _dates The inventories to be returned of `_dates` * @return The inventories */ function inventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates) external view ratePlanExist(_vendorId, _rpid) returns(uint16[]) { require(_dates.length > 0); uint16[] memory result = new uint16[](_dates.length); for (uint256 index = 0; index < _dates.length; index++) { uint256 date = _dates[index]; (uint16 inventory,) = dataSource.getInventory(_vendorId, _rpid, date); result[index] = inventory; } return result; } /** * @dev Returns the prices of `_vendor`'s RP(`_rpid`) on `_dates` * Throw when `_rpid` not exist * Throw when `_dates`'s count lte 0 * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _dates The inventories to be returned of `_dates` * @param _token The digital currency token * @return The prices */ function pricesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token) external view ratePlanExist(_vendorId, _rpid) returns(uint256[]) { require(_dates.length > 0); uint256[] memory result = new uint256[](_dates.length); for (uint256 index = 0; index < _dates.length; index++) { (,, uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _dates[index], _token); result[index] = _price; } return result; } /** * @dev Returns the prices and inventories of `_vendor`'s RP(`_rpid`) on `_dates` * Throw when `_rpid` not exist * Throw when `_dates`'s count lte 0 * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _dates The inventories to be returned of `_dates` * @param _token The digital currency token * @return The prices and inventories */ function pricesAndInventoriesOfDate(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token) external view returns(uint256[], uint16[]) { uint256[] memory prices = new uint256[](_dates.length); uint16[] memory inventories = new uint16[](_dates.length); for (uint256 index = 0; index < _dates.length; index++) { (uint16 _inventory,, uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _dates[index], _token); prices[index] = _price; inventories[index] = _inventory; } return (prices, inventories); } /** * @dev Returns the RP's price and inventory of `_date`. * Throw when `_rpid` not exist * @param _vendorId The vendor Id * @param _rpid The rate plan identifier * @param _date The price and inventory to be returneed of `_date` * @param _token The digital currency token * @return The price and inventory */ function priceOfDate(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token) external view ratePlanExist(_vendorId, _rpid) returns(uint16 _inventory, uint256 _price) { (_inventory, , _price) = dataSource.getPrice(_vendorId, _rpid, _date, _token); } } /** * This utility library was forked from https://github.com/o0ragman0o/LibCLL */ library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList { mapping (uint256 => mapping (bool => uint256)) list; uint256 length; uint256 index; } /** * @dev returns true if the list exists * @param self stored linked list from contract */ function listExists(LinkedList storage self) internal view returns (bool) { return self.length > 0; } /** * @dev returns true if the node exists * @param self stored linked list from contract * @param _node a node to search for */ function nodeExists(LinkedList storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract */ function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) { return self.length; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get */ function getNode(LinkedList storage self, uint256 _node) public view returns (bool, uint256, uint256) { if (!nodeExists(self,_node)) { return (false, 0, 0); } else { return (true, self.list[_node][PREV], self.list[_node][NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in */ function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool, uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } /** * @dev Can be used before `insert` to build an ordered list * @param self stored linked list from contract * @param _node an existing node to search from, e.g. HEAD. * @param _value value to seek * @param _direction direction to seek in * @return next first node beyond '_node' in direction `_direction` */ function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node first node for linking * @param _link node to link to in the _direction */ function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in */ function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); self.length++; return true; } else { return false; } } /** * @dev removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list */ function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; self.length--; return _node; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _index The node Id * @param _direction push to the head (NEXT) or tail (PREV) */ function add(LinkedList storage self, uint256 _index, bool _direction) internal returns (uint256) { insert(self, HEAD, _index, _direction); return self.index; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _direction push to the head (NEXT) or tail (PREV) */ function push(LinkedList storage self, bool _direction) internal returns (uint256) { self.index++; insert(self, HEAD, self.index, _direction); return self.index; } /** * @dev pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (NEXT) or the tail (PREV) */ function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } contract TripioToken { string public name; string public symbol; uint8 public decimals; function transfer(address _to, uint256 _value) public returns (bool); function balanceOf(address who) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } contract TripioRoomNightData is Owned { using LinkedListLib for LinkedListLib.LinkedList; // Interface signature of erc165. // bytes4(keccak256("supportsInterface(bytes4)")) bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7; // Interface signature of erc721 metadata. // bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)")); bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd; // Interface signature of erc721. // bytes4(keccak256("balanceOf(address)")) ^ // bytes4(keccak256("ownerOf(uint256)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^ // bytes4(keccak256("transferFrom(address,address,uint256)")) ^ // bytes4(keccak256("approve(address,uint256)")) ^ // bytes4(keccak256("setApprovalForAll(address,bool)")) ^ // bytes4(keccak256("getApproved(uint256)")) ^ // bytes4(keccak256("isApprovedForAll(address,address)")); bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5; // Base URI of token asset string public tokenBaseURI; // Authorized contracts struct AuthorizedContract { string name; address acontract; } mapping (address=>uint256) public authorizedContractIds; mapping (uint256 => AuthorizedContract) public authorizedContracts; LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0); // Rate plan prices struct Price { uint16 inventory; // Rate plan inventory bool init; // Whether the price is initied mapping (uint256 => uint256) tokens; } // Vendor hotel RPs struct RatePlan { string name; // Name of rate plan. uint256 timestamp; // Create timestamp. bytes32 ipfs; // The address of rate plan detail on IPFS. Price basePrice; // The base price of rate plan mapping (uint256 => Price) prices; // date -> Price } // Vendors struct Vendor { string name; // Name of vendor. address vendor; // Address of vendor. uint256 timestamp; // Create timestamp. bool valid; // Whether the vendor is valid(default is true) LinkedListLib.LinkedList ratePlanList; mapping (uint256=>RatePlan) ratePlans; } mapping (address => uint256) public vendorIds; mapping (uint256 => Vendor) vendors; LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0); // Supported digital currencies mapping (uint256 => address) public tokenIndexToAddress; LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0); // RoomNight tokens struct RoomNight { uint256 vendorId; uint256 rpid; uint256 token; // The digital currency token uint256 price; // The digital currency price uint256 timestamp; // Create timestamp. uint256 date; // The checkin date bytes32 ipfs; // The address of rate plan detail on IPFS. } RoomNight[] public roomnights; // rnid -> owner mapping (uint256 => address) public roomNightIndexToOwner; // Owner Account mapping (address => LinkedListLib.LinkedList) public roomNightOwners; // Vendor Account mapping (address => LinkedListLib.LinkedList) public roomNightVendors; // The authorized address for each TRN mapping (uint256 => address) public roomNightApprovals; // The authorized operators for each address mapping (address => mapping (address => bool)) public operatorApprovals; // The applications of room night redund mapping (address => mapping (uint256 => bool)) public refundApplications; // The signature of `onERC721Received(address,uint256,bytes)` // bytes4(keccak256("onERC721Received(address,uint256,bytes)")); bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba; /** * This emits when contract authorized */ event ContractAuthorized(address _contract); /** * This emits when contract deauthorized */ event ContractDeauthorized(address _contract); /** * The contract is valid */ modifier authorizedContractValid(address _contract) { require(authorizedContractIds[_contract] > 0); _; } /** * The contract is valid */ modifier authorizedContractIdValid(uint256 _cid) { require(authorizedContractList.nodeExists(_cid)); _; } /** * Only the owner or authorized contract is valid */ modifier onlyOwnerOrAuthorizedContract { require(msg.sender == owner || authorizedContractIds[msg.sender] > 0); _; } /** * Constructor */ constructor() public { // Add one invalid RoomNight, avoid subscript 0 roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0)); } /** * @dev Returns the node list and next node as a tuple * @param self stored linked list from contract * @param _node the begin id of the node to get * @param _limit the total nodes of one page * @param _direction direction to step in */ function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction) private view returns (uint256[], uint256) { bool exists; uint256 i = 0; uint256 ei = 0; uint256 index = 0; uint256 count = _limit; if(count > self.length) { count = self.length; } (exists, i) = self.getAdjacent(_node, _direction); if(!exists || count == 0) { return (new uint256[](0), 0); }else { uint256[] memory temp = new uint256[](count); if(_node != 0) { index++; temp[0] = _node; } while (i != 0 && index < count) { temp[index] = i; (exists,i) = self.getAdjacent(i, _direction); index++; } ei = i; if(index < count) { uint256[] memory result = new uint256[](index); for(i = 0; i < index; i++) { result[i] = temp[i]; } return (result, ei); }else { return (temp, ei); } } } /** * @dev Authorize `_contract` to execute this contract's funs * @param _contract The contract address * @param _name The contract name */ function authorizeContract(address _contract, string _name) public onlyOwner returns(bool) { uint256 codeSize; assembly { codeSize := extcodesize(_contract) } require(codeSize != 0); // Not exists require(authorizedContractIds[_contract] == 0); // Add uint256 id = authorizedContractList.push(false); authorizedContractIds[_contract] = id; authorizedContracts[id] = AuthorizedContract(_name, _contract); // Event emit ContractAuthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by address * @param _contract The contract address */ function deauthorizeContract(address _contract) public onlyOwner authorizedContractValid(_contract) returns(bool) { uint256 id = authorizedContractIds[_contract]; authorizedContractList.remove(id); authorizedContractIds[_contract] = 0; delete authorizedContracts[id]; // Event emit ContractDeauthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by contract id * @param _cid The contract id */ function deauthorizeContractById(uint256 _cid) public onlyOwner authorizedContractIdValid(_cid) returns(bool) { address acontract = authorizedContracts[_cid].acontract; authorizedContractList.remove(_cid); authorizedContractIds[acontract] = 0; delete authorizedContracts[_cid]; // Event emit ContractDeauthorized(acontract); return true; } /** * @dev Get authorize contract ids by page * @param _from The begin authorize contract id * @param _limit How many authorize contract ids one page * @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0 */ function getAuthorizeContractIds(uint256 _from, uint256 _limit) external view returns(uint256[], uint256){ return getNodes(authorizedContractList, _from, _limit, true); } /** * @dev Get authorize contract by id * @param _cid Then authorize contract id * @return The authorize contract info(_name, _acontract) */ function getAuthorizeContract(uint256 _cid) external view returns(string _name, address _acontract) { AuthorizedContract memory acontract = authorizedContracts[_cid]; _name = acontract.name; _acontract = acontract.acontract; } /*************************************** GET ***************************************/ /** * @dev Get the rate plan by `_vendorId` and `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function getRatePlan(uint256 _vendorId, uint256 _rpid) public view returns (string _name, uint256 _timestamp, bytes32 _ipfs) { _name = vendors[_vendorId].ratePlans[_rpid].name; _timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp; _ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs; } /** * @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId) public view returns(uint16 _inventory, bool _init, uint256 _price) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; _price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId]; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; _price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; _init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } } /** * @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _dates The dates desc ([20180723,20180724,20180725]) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId) public view returns(uint16[] _inventories, uint256[] _prices) { uint16[] memory inventories = new uint16[](_dates.length); uint256[] memory prices = new uint256[](_dates.length); uint256 date; for(uint256 i = 0; i < _dates.length; i++) { date = _dates[i]; uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory; bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init; uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId]; if(!init) { // Get the base price inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } inventories[i] = inventory; prices[i] = price; } return (inventories, prices); } /** * @dev Get the inventory by by `_vendorId`, `_rpid` and `_date` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @return The inventory info(inventory, init) */ function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date) public view returns(uint16 _inventory, bool _init) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; } } /** * @dev Whether the rate plan is exist * @param _vendorId The vendor id * @param _rpid The rate plan id * @return If the rate plan of the vendor is exist returns true otherwise return false */ function ratePlanIsExist(uint256 _vendorId, uint256 _rpid) public view returns (bool) { return vendors[_vendorId].ratePlanList.nodeExists(_rpid); } /** * @dev Get orders of owner by page * @param _owner The owner address * @param _from The begin id of the node to get * @param _limit The total nodes of one page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightOwners[_owner], _from, _limit, _direction); } /** * @dev Get orders of vendor by page * @param _owner The vendor address * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightVendors[_owner], _from, _limit, _direction); } /** * @dev Get the token count of somebody * @param _owner The owner of token * @return The token count of `_owner` */ function balanceOf(address _owner) public view returns(uint256) { return roomNightOwners[_owner].length; } /** * @dev Get rate plan ids of `_vendorId` * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The rate plan ids and the next id */ function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction); } /** * @dev Get token ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The token ids and the next id */ function getTokens(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(tokenList, _from, _limit, _direction); } /** * @dev Get token Info * @param _tokenId The token id * @return The token info(symbol, name, decimals) */ function getToken(uint256 _tokenId) public view returns(string _symbol, string _name, uint8 _decimals, address _token) { _token = tokenIndexToAddress[_tokenId]; TripioToken tripio = TripioToken(_token); _symbol = tripio.symbol(); _name = tripio.name(); _decimals = tripio.decimals(); } /** * @dev Get vendor ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The vendor ids and the next id */ function getVendors(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendorList, _from, _limit, _direction); } /** * @dev Get the vendor infomation by vendorId * @param _vendorId The vendor id * @return The vendor infomation(name, vendor, timestamp, valid) */ function getVendor(uint256 _vendorId) public view returns(string _name, address _vendor,uint256 _timestamp, bool _valid) { _name = vendors[_vendorId].name; _vendor = vendors[_vendorId].vendor; _timestamp = vendors[_vendorId].timestamp; _valid = vendors[_vendorId].valid; } /*************************************** SET ***************************************/ /** * @dev Update base uri of token metadata * @param _tokenBaseURI The base uri */ function updateTokenBaseURI(string _tokenBaseURI) public onlyOwnerOrAuthorizedContract { tokenBaseURI = _tokenBaseURI; } /** * @dev Push order to user's order list * @param _owner The buyer address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightOwners[_owner].listExists()) { roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0); } roomNightOwners[_owner].add(_rnid, _direction); } /** * @dev Remove order from owner's order list * @param _owner The owner address * @param _rnid The room night order id */ function removeOrderOfOwner(address _owner, uint _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightOwners[_owner].nodeExists(_rnid)); roomNightOwners[_owner].remove(_rnid); } /** * @dev Push order to the vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightVendors[_vendor].listExists()) { roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0); } roomNightVendors[_vendor].add(_rnid, _direction); } /** * @dev Remove order from vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id */ function removeOrderOfVendor(address _vendor, uint256 _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightVendors[_vendor].nodeExists(_rnid)); roomNightVendors[_vendor].remove(_rnid); } /** * @dev Transfer token to somebody * @param _tokenId The token id * @param _to The target owner of the token */ function transferTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightIndexToOwner[_tokenId] = _to; roomNightApprovals[_tokenId] = address(0); } /** * @dev Approve `_to` to operate the `_tokenId` * @param _tokenId The token id * @param _to Somebody to be approved */ function approveTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightApprovals[_tokenId] = _to; } /** * @dev Approve `_operator` to operate all the Token of `_to` * @param _operator The operator to be approved * @param _to The owner of tokens to be operate * @param _approved Approved or not */ function approveOperatorTo(address _operator, address _to, bool _approved) public onlyOwnerOrAuthorizedContract { operatorApprovals[_to][_operator] = _approved; } /** * @dev Update base price of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _tokenId The digital token id * @param _price The price to be updated */ function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.init = true; vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price; } /** * @dev Update base inventory of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _inventory The inventory to be updated */ function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory; } /** * @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated */ function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The inventory to be updated */ function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); } } /** * @dev Reduce inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be reduced */ function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 a = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){ a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory; } } /** * @dev Add inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be add */ function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 c = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c; } } /** * @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated * @param _inventory The inventory to be updated */ function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Push rate plan to `_vendorId`'s rate plan list * @param _vendorId The vendor id * @param _name The name of rate plan * @param _ipfs The rate plan IPFS address * @param _direction direction to step in */ function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false)); uint256 id = vendors[_vendorId].ratePlanList.push(_direction); vendors[_vendorId].ratePlans[id] = rp; return id; } /** * @dev Remove rate plan of `_vendorId` by `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function removeRatePlan(uint256 _vendorId, uint256 _rpid) public onlyOwnerOrAuthorizedContract { delete vendors[_vendorId].ratePlans[_rpid]; vendors[_vendorId].ratePlanList.remove(_rpid); } /** * @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _name The rate plan name * @param _ipfs The rate plan IPFS address */ function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs; vendors[_vendorId].ratePlans[_rpid].name = _name; } /** * @dev Push token contract to the token list * @param _direction direction to step in */ function pushToken(address _contract, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = tokenList.push(_direction); tokenIndexToAddress[id] = _contract; return id; } /** * @dev Remove token by `_tokenId` * @param _tokenId The digital token id */ function removeToken(uint256 _tokenId) public onlyOwnerOrAuthorizedContract { delete tokenIndexToAddress[_tokenId]; tokenList.remove(_tokenId); } /** * @dev Generate room night token * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _token The token id * @param _price The token price * @param _ipfs The rate plan IPFS address */ function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract returns(uint256) { roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs)); // Give the token to `_customer` uint256 rnid = uint256(roomnights.length - 1); return rnid; } /** * @dev Update refund applications * @param _buyer The room night token holder * @param _rnid The room night token id * @param _isRefund Is redund or not */ function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund) public onlyOwnerOrAuthorizedContract { refundApplications[_buyer][_rnid] = _isRefund; } /** * @dev Push vendor info to the vendor list * @param _name The name of vendor * @param _vendor The vendor address * @param _direction direction to step in */ function pushVendor(string _name, address _vendor, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = vendorList.push(_direction); vendorIds[_vendor] = id; vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0)); return id; } /** * @dev Remove vendor from vendor list * @param _vendorId The vendor id */ function removeVendor(uint256 _vendorId) public onlyOwnerOrAuthorizedContract { vendorList.remove(_vendorId); address vendor = vendors[_vendorId].vendor; vendorIds[vendor] = 0; delete vendors[_vendorId]; } /** * @dev Make vendor valid or invalid * @param _vendorId The vendor id * @param _valid The vendor is valid or not */ function updateVendorValid(uint256 _vendorId, bool _valid) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].valid = _valid; } /** * @dev Modify vendor's name * @param _vendorId The vendor id * @param _name Then vendor name */ function updateVendorName(uint256 _vendorId, string _name) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].name = _name; } } contract TRNRatePlans is TRNData { /** * Constructor */ constructor() public { } /** * This emits when rate plan created */ event RatePlanCreated(address indexed _vendor, string _name, bytes32 indexed _ipfs); /** * This emits when rate plan removed */ event RatePlanRemoved(address indexed _vendor, uint256 indexed _rpid); /** * This emits when rate plan modified */ event RatePlanModified(address indexed _vendor, uint256 indexed _rpid, string name, bytes32 _ipfs); /** * @dev Create rate plan * Only vendor can operate * Throw when `_name`'s length lte 0 or mte 100. * @param _name The name of rate plan * @param _ipfs The address of the rate plan detail info on IPFS. */ function createRatePlan(string _name, bytes32 _ipfs) external // onlyVendor returns(uint256) { // if vendor not exist create it if(dataSource.vendorIds(msg.sender) == 0) { dataSource.pushVendor("", msg.sender, false); } bytes memory nameBytes = bytes(_name); require(nameBytes.length > 0 && nameBytes.length < 200); uint256 vendorId = dataSource.vendorIds(msg.sender); uint256 id = dataSource.pushRatePlan(vendorId, _name, _ipfs, false); // Event emit RatePlanCreated(msg.sender, _name, _ipfs); return id; } /** * @dev Remove rate plan * Only vendor can operate * Throw when `_rpid` not exist * @param _rpid The rate plan identifier */ function removeRatePlan(uint256 _rpid) external onlyVendor ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { uint256 vendorId = dataSource.vendorIds(msg.sender); // Delete rate plan dataSource.removeRatePlan(vendorId, _rpid); // Event emit RatePlanRemoved(msg.sender, _rpid); return true; } /** * @dev Modify rate plan * Throw when `_rpid` not exist * @param _rpid The rate plan identifier * @param _ipfs The address of the rate plan detail info on IPFS */ function modifyRatePlan(uint256 _rpid, string _name, bytes32 _ipfs) external onlyVendor ratePlanExist(dataSource.vendorIds(msg.sender), _rpid) returns(bool) { uint256 vendorId = dataSource.vendorIds(msg.sender); dataSource.updateRatePlan(vendorId, _rpid, _name, _ipfs); // Event emit RatePlanModified(msg.sender, _rpid, _name, _ipfs); return true; } /** * @dev Returns a list of all rate plan IDs assigned to a vendor. * @param _vendorId The Id of vendor * @param _from The begin ratePlan Id * @param _limit How many ratePlan Ids one page * @return A list of all rate plan IDs assigned to a vendor */ function ratePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit) external view vendorIdValid(_vendorId) returns(uint256[], uint256) { return dataSource.getRatePlansOfVendor(_vendorId, _from, _limit, true); } /** * @dev Returns ratePlan info of vendor * @param _vendorId The address of vendor * @param _rpid The ratePlan id * @return The ratePlan info(_name, _timestamp, _ipfs) */ function ratePlanOfVendor(uint256 _vendorId, uint256 _rpid) external view vendorIdValid(_vendorId) returns(string _name, uint256 _timestamp, bytes32 _ipfs) { (_name, _timestamp, _ipfs) = dataSource.getRatePlan(_vendorId, _rpid); } } contract TripioRoomNightVendor is TRNPrices, TRNRatePlans { /** * Constructor */ constructor(address _dataSource) public { // Init the data source dataSource = TripioRoomNightData(_dataSource); } /** * @dev Destory the contract */ function destroy() external onlyOwner { selfdestruct(owner); } }
* This emits when rate plan price changed/
event RatePlanPriceChanged(uint256 indexed _rpid);
10,201,744
[ 1, 2503, 24169, 1347, 4993, 4995, 6205, 3550, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 13025, 5365, 5147, 5033, 12, 11890, 5034, 8808, 389, 86, 6610, 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 ]
// Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.5; pragma experimental ABIEncoderV2; interface ERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // ERC20-style token metadata // 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE address is used for ETH struct TokenMetadata { address token; string name; string symbol; uint8 decimals; } struct Component { address token; // Address of token contract string tokenType; // Token type ("ERC20" by default) uint256 rate; // Price per full share (1e18) } /** * @title Token adapter interface. * @dev getMetadata() and getComponents() functions MUST be implemented. * @author Igor Sobolev <[email protected]> */ interface TokenAdapter { /** * @dev MUST return TokenMetadata struct with ERC20-style token info. * struct TokenMetadata { * address token; * string name; * string symbol; * uint8 decimals; * } */ function getMetadata(address token) external view returns (TokenMetadata memory); /** * @dev MUST return array of Component structs with underlying tokens rates for the given token. * struct Component { * address token; // Address of token contract * string tokenType; // Token type ("ERC20" by default) * uint256 rate; // Price per full share (1e18) * } */ function getComponents(address token) external view returns (Component[] memory); } /** * @dev SetToken contract interface. * Only the functions required for TokenSetsTokenAdapter contract are added. * The SetToken contract is available here * github.com/SetProtocol/set-protocol-contracts/blob/master/contracts/core/tokens/SetToken.sol. */ interface SetToken { function getUnits() external view returns (uint256[] memory); function naturalUnit() external view returns (uint256); function getComponents() external view returns(address[] memory); } /** * @dev RebalancingSetToken contract interface. * Only the functions required for TokenSetsTokenAdapter contract are added. * The RebalancingSetToken contract is available here * github.com/SetProtocol/set-protocol-contracts/blob/master/contracts/core/tokens/RebalancingSetTokenV3.sol. */ interface RebalancingSetToken { function unitShares() external view returns (uint256); function naturalUnit() external view returns (uint256); function currentSet() external view returns (SetToken); } /** * @title Token adapter for TokenSets. * @dev Implementation of TokenAdapter interface. * @author Igor Sobolev <[email protected]> */ contract TokenSetsTokenAdapter is TokenAdapter { /** * @return TokenMetadata struct with ERC20-style token info. * @dev Implementation of TokenAdapter interface function. */ function getMetadata(address token) external view override returns (TokenMetadata memory) { return TokenMetadata({ token: token, name: ERC20(token).name(), symbol: ERC20(token).symbol(), decimals: ERC20(token).decimals() }); } /** * @return Array of Component structs with underlying tokens rates for the given token. * @dev Implementation of TokenAdapter interface function. */ function getComponents(address token) external view override returns (Component[] memory) { RebalancingSetToken rebalancingSetToken = RebalancingSetToken(token); uint256 tokenUnitShare = rebalancingSetToken.unitShares(); uint256 tokenNaturalUnit = rebalancingSetToken.naturalUnit(); uint256 tokenRate = 1e18 * tokenUnitShare / tokenNaturalUnit; SetToken setToken = rebalancingSetToken.currentSet(); uint256[] memory unitShares = setToken.getUnits(); uint256 naturalUnit = setToken.naturalUnit(); address[] memory components = setToken.getComponents(); Component[] memory underlyingTokens = new Component[](components.length); for (uint256 i = 0; i < underlyingTokens.length; i++) { underlyingTokens[i] = Component({ token: components[i], tokenType: "ERC20", rate: tokenRate * unitShares[i] / naturalUnit }); } return underlyingTokens; } }
Price per full share (1e18)
uint256 rate;
601,165
[ 1, 5147, 1534, 1983, 7433, 261, 21, 73, 2643, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4993, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; // SPDX-License-Identifier: BSD-3-Clause /** * Vaults Reward Fund Locked till 20th Oct 2020 * Farming vault token will transfer on Vaults smart contrcat after unlock which will be without withdrawal permission * */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; address public pendingOwner; 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()); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyPendingOwner() { assert(msg.sender != address(0)); require(msg.sender == pendingOwner); _; } /** * @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 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)); pendingOwner = _newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { _transferOwnership(pendingOwner); pendingOwner = address(0); } /** * @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; } } interface token { function transfer(address, uint) external returns (bool); } contract TokenLock is Ownable { address public constant beneficiary = 0x3E7e36f4Dd5394E48ce3D5dB86D71F062B18aE1B; // unlock timestamp in seconds (Oct 20 2020 UTC) uint public constant unlockTime = 1603152000; function isUnlocked() public view returns (bool) { return now > unlockTime; } function claim(address _tokenAddr, uint _amount) public onlyOwner { require(isUnlocked(), "Cannot transfer tokens while locked."); token(_tokenAddr).transfer(beneficiary, _amount); } }
unlock timestamp in seconds (Oct 20 2020 UTC)
contract TokenLock is Ownable { address public constant beneficiary = 0x3E7e36f4Dd5394E48ce3D5dB86D71F062B18aE1B; uint public constant unlockTime = 1603152000; function isUnlocked() public view returns (bool) { return now > unlockTime; } function claim(address _tokenAddr, uint _amount) public onlyOwner { require(isUnlocked(), "Cannot transfer tokens while locked."); token(_tokenAddr).transfer(beneficiary, _amount); } }
15,419,622
[ 1, 26226, 2858, 316, 3974, 261, 19320, 4200, 26599, 20, 9951, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 2531, 353, 14223, 6914, 288, 203, 377, 203, 203, 565, 1758, 1071, 5381, 27641, 74, 14463, 814, 273, 374, 92, 23, 41, 27, 73, 5718, 74, 24, 40, 72, 25, 5520, 24, 41, 8875, 311, 23, 40, 25, 72, 38, 5292, 40, 11212, 42, 7677, 22, 38, 2643, 69, 41, 21, 38, 31, 203, 203, 377, 203, 565, 2254, 1071, 5381, 7186, 950, 273, 2872, 4630, 3600, 17172, 31, 203, 203, 565, 445, 353, 7087, 329, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2037, 405, 7186, 950, 31, 203, 565, 289, 203, 377, 203, 565, 445, 7516, 12, 2867, 389, 2316, 3178, 16, 2254, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 291, 7087, 329, 9334, 315, 4515, 7412, 2430, 1323, 8586, 1199, 1769, 203, 3639, 1147, 24899, 2316, 3178, 2934, 13866, 12, 70, 4009, 74, 14463, 814, 16, 389, 8949, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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 {} } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @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; } } /* * Interface for the $COLORWASTE erc20 token contract */ interface ICW { function burn(address _from, uint256 _amount) external; function updateBalance(address _from, address _to) external; } /* * Interface for the $SOS erc20 token contract */ interface ISOS { function approve(address from, uint256 amount) external returns(bool); function transferFrom(address from, address to, uint256 amount) external; function balanceOf(address owner) external view returns(uint256); } /* * Interface for the Doodles contract */ interface IDoodles { function balanceOf(address owner) external view returns(uint256); function ownerOf(uint256 tokenId) external view returns(address); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns(uint256); } /* * Interface for the KaijuKingz contract */ interface IKaijuKingz { function walletOfOwner(address owner) external view returns(uint256[] memory); function ownerOf(uint256 tokenId) external view returns(address); } /* * DAIJUKINGZ */ contract DaijuKingz is ERC721, Ownable { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; Counters.Counter private TotalSupplyFix; ICW public CW; IDoodles public Doodles; IKaijuKingz public KaijuKingz; ISOS public SOS; string private baseURI; uint256 constant public reserveMax = 50; // the amount of daijus the team will reserve for community events, staff, etc. uint256 public maxSupply = 11110; // max genesis + max bred daijus uint256 public maxGenCount = 5555; // the max genesis count. if theres remaining supply after sale ends, the genesis daijukingz will be less then this number uint256 public maxFreeMints = 124; // the max free mints that can be claimed for kaiju and doodle holders uint256 public maxGivewayMint = 676; // the max free mints that are from the whitelisted users // counters uint256 public reserveCount = 0; uint256 public freeMintCount = 0; uint256 public giveawayMintCount = 0; uint256 public genCount = 0; uint256 public babyCount = 0; // settings for breeding & sales uint256 public price = 0.05 ether; uint256 public breedPrice = 7500 ether; uint256 public increasePerBreed = 0 ether; uint256 public saleStartTimestamp; uint256 public freeEndTimestamp; address public sosWallet; uint256 public sosPrice = 0.05 ether; bool public transfersEnabled = false; bool public breedingEnabled = false; // tracks all of the wallets that interact with the contract mapping(address => uint256) public balanceGenesis; mapping(address => uint256) public balanceBaby; mapping(address => uint256) public freeMintList; mapping(address => uint256) public giveawayMintList; /* * DaijuOwner * checks if the token IDs provided are owned by the user interacting with the contract (used for breeding) */ modifier DaijuOwner(uint256 DaijuId) { require(ownerOf(DaijuId) == msg.sender, "Cannot interact with a DaijuKingz you do not own"); _; } /* * IsSaleActive * checks if the mint is ready to begin */ modifier IsSaleActive() { require(saleStartTimestamp != 0 && block.timestamp > saleStartTimestamp, "Cannot interact because sale has not started"); _; } /* * IsFreeMintActive * checks if the free mint end timestamp isn't met */ modifier IsFreeMintActive { require(block.timestamp < freeEndTimestamp, "Free Minting period has ended!"); _; } /* * AreTransfersEnabled * checks if we want to allow opensea to transfer any tokens */ modifier AreTransfersEnabled() { require(transfersEnabled, "Transfers aren't allowed yet!"); _; } constructor() ERC721("DaijuKingz", "Daiju") {} /* * mintFreeKaijuList * checks the walelt for a list of kaijukingz they hold, used for checking if they * can claim a free daijuking */ function mintFreeKaijuList(address _address) external view returns(uint256[] memory) { return KaijuKingz.walletOfOwner(_address); } /* * mintFreeDoodleList * gets the amount of doodles a wallet holds, used for checking if they are elligble * for claiming a free daijuking */ function mintFreeDoodleList(address _address) public view returns(uint256) { uint256 count = Doodles.balanceOf(_address); return count; } /* * checkIfFreeMintClaimed * checks if the address passed claimed a free mint already */ function checkIfFreeMintClaimed(address _address) public view returns(uint256) { return freeMintList[_address]; } /* * checkIfGiveawayMintClaimed * checks if they claimed their giveaway mint */ function checkIfGiveawayMintClaimed(address _address) public view returns(uint256) { return giveawayMintList[_address]; } /* * addGiveawayWinners * adds the wallets to the giveaway list so they can call mintFreeGiveaway() */ function addGiveawayWinners(address[] calldata giveawayAddresses) external onlyOwner { for (uint256 i; i < giveawayAddresses.length; i++) { giveawayMintList[giveawayAddresses[i]] = 1; } } /* * mintFreeDoodle * mints a free daijuking using a Doodles token - can only be claimed once per wallet */ function mintFreeDoodle() public payable IsSaleActive IsFreeMintActive { uint256 supply = TotalSupplyFix.current(); require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!"); require(mintFreeDoodleList(msg.sender) >= 1, "You don't own any Doodles!"); require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!"); require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!"); require(!breedingEnabled, "Minting genesis has been disabled!"); _safeMint(msg.sender, supply); TotalSupplyFix.increment(); freeMintList[msg.sender] = 1; balanceGenesis[msg.sender]++; genCount++; freeMintCount += 1; } /* * mintFreeKaiju * mints a free daijuking using a KaijuKingz token - can only be claimed once per wallet */ function mintFreeKaiju() public payable IsSaleActive IsFreeMintActive { uint256 supply = TotalSupplyFix.current(); uint256[] memory list = KaijuKingz.walletOfOwner(msg.sender); require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!"); require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!"); require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!"); require(list.length >= 1, "You don't own any KaijuKingz!"); require(!breedingEnabled, "Minting genesis has been disabled!"); _safeMint(msg.sender, supply); TotalSupplyFix.increment(); freeMintList[msg.sender] = 1; balanceGenesis[msg.sender]++; genCount++; freeMintCount += 1; } /* * mintFreeGiveaway * this is for the giveaway winners - allows you to mint a free daijuking */ function mintFreeGiveaway() public payable IsSaleActive IsFreeMintActive { uint256 supply = TotalSupplyFix.current(); require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!"); require((supply + 1) <= maxGivewayMint, "All giveaway mints were claimed!"); require(giveawayMintList[msg.sender] >= 1, "You don't have any free mints left!"); require(!breedingEnabled, "Minting genesis has been disabled!"); _safeMint(msg.sender, supply); TotalSupplyFix.increment(); giveawayMintList[msg.sender] = 0; balanceGenesis[msg.sender]++; genCount++; giveawayMintCount += 1; } /* * mint * mints the daijuking using ETH as the payment token */ function mint(uint256 numberOfMints) public payable IsSaleActive { uint256 supply = TotalSupplyFix.current(); require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount"); if (block.timestamp <= freeEndTimestamp) { require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), "Purchase would exceed max supply"); } else { require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply"); } require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct"); require(!breedingEnabled, "Minting genesis has been disabled!"); for (uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, supply + i); balanceGenesis[msg.sender]++; genCount++; TotalSupplyFix.increment(); } } /* * mintWithSOS * allows the user to mint a daijuking using the $SOS token * note: user must approve it before this can be called */ function mintWithSOS(uint256 numberOfMints) public payable IsSaleActive { uint256 supply = TotalSupplyFix.current(); require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount"); require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply"); require(sosPrice.mul(numberOfMints) < SOS.balanceOf(msg.sender), "Not enough SOS to mint!"); require(!breedingEnabled, "Minting genesis has been disabled!"); SOS.transferFrom(msg.sender, sosWallet, sosPrice.mul(numberOfMints)); for (uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, supply + i); balanceGenesis[msg.sender]++; genCount++; TotalSupplyFix.increment(); } } /* * breed * allows you to create a daijuking using 2 parents and some $COLORWASTE, 18+ only * note: selecting is automatic from the DAPP, but if you use the contract make sure they are two unique token id's that aren't children... */ function breed(uint256 parent1, uint256 parent2) public DaijuOwner(parent1) DaijuOwner(parent2) { uint256 supply = TotalSupplyFix.current(); require(breedingEnabled, "Breeding isn't enabled yet!"); require(supply < maxSupply, "Cannot breed any more baby Daijus"); require(parent1 < genCount && parent2 < genCount, "Cannot breed with baby Daijus (thats sick bro)"); require(parent1 != parent2, "Must select two unique parents"); // burns the tokens for the breeding cost CW.burn(msg.sender, breedPrice + increasePerBreed * babyCount); // adds the baby to the total supply and counter babyCount++; TotalSupplyFix.increment(); // mints the baby daijuking and adds it to the balance for the wallet _safeMint(msg.sender, supply); balanceBaby[msg.sender]++; } /* * reserve * mints the reserved amount */ function reserve(uint256 count) public onlyOwner { uint256 supply = TotalSupplyFix.current(); require(reserveCount + count < reserveMax, "cannot reserve more"); for (uint256 i = 0; i < count; i++) { _safeMint(msg.sender, supply + i); balanceGenesis[msg.sender]++; genCount++; TotalSupplyFix.increment(); reserveCount++; } } /* * totalSupply * returns the current amount of tokens, called by DAPPs */ function totalSupply() external view returns(uint256) { return TotalSupplyFix.current(); } /* * getTypes * gets the tokens provided and returns the genesis and baby daijukingz * * genesis is 0 * baby is 1 */ function getTypes(uint256[] memory list) external view returns(uint256[] memory) { uint256[] memory typeList = new uint256[](list.length); for (uint256 i; i < list.length; i++){ if (list[i] >= genCount) { typeList[i] = 1; } else { typeList[i] = 0; } } return typeList; } /* * walletOfOwner * returns the tokens that the user owns */ function walletOfOwner(address owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(owner); uint256 supply = TotalSupplyFix.current(); uint256 index = 0; uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < supply; i++) { if (ownerOf(i) == owner) { tokensId[index] = i; index++; } } return tokensId; } /* * withdraw * takes out the eth from the contract to the deployer */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /* * updateSaleTimestamp * set once we're ready release */ function updateSaleTimestamp(uint256 _saleStartTimestamp) public onlyOwner { saleStartTimestamp = _saleStartTimestamp; } /* * updateFreeEndTimestamp * set once saleStartTimestamp is set for release */ function updateFreeEndTimestamp(uint256 _freeEndTimestamp) public onlyOwner { freeEndTimestamp = _freeEndTimestamp; } /* * setBreedingCost * sets the breeding cost to the new */ function setBreedingCost(uint256 _breedPrice) public onlyOwner { breedPrice = _breedPrice; } /* * setBreedingCostIncrease * change the rate based on the breeding cost for each new baby mint */ function setBreedingCostIncrease(uint256 _increasePerBreed) public onlyOwner { increasePerBreed = _increasePerBreed; } /* * setBreedingState * changes whether breeding is enabled or not, by default its disabled */ function setBreedingState(bool _state) public onlyOwner { breedingEnabled = _state; } /* * setPrice * sets the eth mint price (shouldn't ever be called but who knows) */ function setPrice(uint256 _price) public onlyOwner { price = _price; } /* * setSOSPrice * sets the price for $SOS mint, most likely will only be set once before the release */ function setSOSPrice(uint256 _sosPrice) public onlyOwner { sosPrice = _sosPrice; } // 46524939000000000000000000 // 4652493900000000000000000 /* * setSOSWallet * sets the deposit wallet for $SOS mints */ function setSOSWallet(address _address) public onlyOwner { sosWallet = _address; } /* * setBaseURI * sets the metadata url once its live */ function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } /* * _baseURI * returns the metadata url to any DAPPs that use it (opensea for instance) */ function _baseURI() internal view override returns (string memory) { return baseURI; } /* * setTransfersEnabled * enables opensea transfers - can only be called once */ function setTransfersEnabled() external onlyOwner { transfersEnabled = true; } /* * setCWInterface * links the interface to the $COLORWASTE smart contract once it's deployed */ function setCWInterface(address _address) external onlyOwner { CW = ICW(_address); } /* * setKaijuInterface * links the interface to the KaijuKingz contract */ function setKaijuInterface(address _address) public onlyOwner { KaijuKingz = IKaijuKingz(_address); } /* * setDoodleInterface * links the interface to the Doodles contract */ function setDoodleInterface(address _address) public onlyOwner { Doodles = IDoodles(_address); } /* * setSOSInterface * links the interface to the $SOS contract */ function setSOSInterface(address target) public onlyOwner { SOS = ISOS(target); } /* * Opensea methods for transfering the tokens */ function transferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled { CW.updateBalance(from, to); if (tokenId >= maxGenCount) { balanceBaby[from]--; balanceBaby[to]++; } else { balanceGenesis[from]--; balanceGenesis[to]++; } ERC721.transferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override AreTransfersEnabled { CW.updateBalance(from, to); if (tokenId >= maxGenCount) { balanceBaby[from]--; balanceBaby[to]++; } else { balanceGenesis[from]--; balanceGenesis[to]++; } ERC721.safeTransferFrom(from, to, tokenId, data); } }
mint mints the daijuking using ETH as the payment token/
function mint(uint256 numberOfMints) public payable IsSaleActive { uint256 supply = TotalSupplyFix.current(); require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount"); if (block.timestamp <= freeEndTimestamp) { require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), "Purchase would exceed max supply"); require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply"); } require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct"); require(!breedingEnabled, "Minting genesis has been disabled!"); for (uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, supply + i); balanceGenesis[msg.sender]++; genCount++; TotalSupplyFix.increment(); } }
6,906,515
[ 1, 81, 474, 312, 28142, 326, 5248, 8302, 19445, 310, 1450, 512, 2455, 487, 326, 5184, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 11890, 5034, 7922, 49, 28142, 13, 1071, 8843, 429, 2585, 30746, 3896, 288, 203, 3639, 2254, 5034, 14467, 273, 10710, 3088, 1283, 8585, 18, 2972, 5621, 203, 3639, 2583, 12, 2696, 951, 49, 28142, 405, 374, 597, 7922, 49, 28142, 411, 4648, 16, 315, 1941, 23701, 3844, 8863, 203, 203, 3639, 309, 261, 2629, 18, 5508, 1648, 4843, 1638, 4921, 13, 288, 203, 5411, 2583, 12, 2859, 1283, 18, 1289, 12, 2696, 951, 49, 28142, 13, 1648, 261, 1896, 7642, 1380, 300, 261, 1896, 9194, 49, 28142, 397, 943, 43, 427, 359, 528, 49, 474, 13, 3631, 315, 23164, 4102, 9943, 943, 14467, 8863, 203, 5411, 2583, 12, 2859, 1283, 18, 1289, 12, 2696, 951, 49, 28142, 13, 1648, 943, 7642, 1380, 16, 315, 23164, 4102, 9943, 943, 14467, 8863, 203, 3639, 289, 203, 540, 203, 3639, 2583, 12, 8694, 18, 16411, 12, 2696, 951, 49, 28142, 13, 422, 1234, 18, 1132, 16, 315, 41, 1136, 460, 3271, 353, 486, 3434, 8863, 203, 3639, 2583, 12, 5, 6073, 329, 310, 1526, 16, 315, 49, 474, 310, 21906, 711, 2118, 5673, 4442, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 7922, 49, 28142, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 14467, 397, 277, 1769, 203, 5411, 11013, 7642, 16786, 63, 3576, 18, 15330, 3737, 15, 31, 203, 5411, 3157, 1380, 9904, 31, 203, 5411, 10710, 3088, 1283, 8585, 18, 15016, 5621, 203, 3639, 289, 203, 565, 289, 203, 2 ]
./partial_match/1/0x77a13ccd9B3983ee24513f0845c8deffC1874E12/sources/TigerQueen.sol
Liquidation will not process below this token balance
uint256 public minTokensToLiquidate;
15,945,343
[ 1, 48, 18988, 350, 367, 903, 486, 1207, 5712, 333, 1147, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1071, 1131, 5157, 774, 48, 18988, 350, 340, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; contract IStructuredStorage { function setProxyLogicContractAndDeployer(address _proxyLogicContract, address _deployer) external; function setProxyLogicContract(address _proxyLogicContract) external; // *** Getter Methods *** function getUint(bytes32 _key) external view returns(uint); function getString(bytes32 _key) external view returns(string); function getAddress(bytes32 _key) external view returns(address); function getBytes(bytes32 _key) external view returns(bytes); function getBool(bytes32 _key) external view returns(bool); function getInt(bytes32 _key) external view returns(int); function getBytes32(bytes32 _key) external view returns(bytes32); // *** Getter Methods For Arrays *** function getBytes32Array(bytes32 _key) external view returns (bytes32[]); function getAddressArray(bytes32 _key) external view returns (address[]); function getUintArray(bytes32 _key) external view returns (uint[]); function getIntArray(bytes32 _key) external view returns (int[]); function getBoolArray(bytes32 _key) external view returns (bool[]); // *** Setter Methods *** function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string _value) external; function setAddress(bytes32 _key, address _value) external; function setBytes(bytes32 _key, bytes _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // *** Setter Methods For Arrays *** function setBytes32Array(bytes32 _key, bytes32[] _value) external; function setAddressArray(bytes32 _key, address[] _value) external; function setUintArray(bytes32 _key, uint[] _value) external; function setIntArray(bytes32 _key, int[] _value) external; function setBoolArray(bytes32 _key, bool[] _value) external; // *** Delete Methods *** function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteAddress(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; } contract ITwoKeyAdmin { function getDefaultIntegratorFeePercent() public view returns (uint); function getDefaultNetworkTaxPercent() public view returns (uint); function getTwoKeyRewardsReleaseDate() external view returns(uint); function updateReceivedTokensAsModerator(uint amountOfTokens) public; function updateReceivedTokensAsModeratorPPC(uint amountOfTokens, address campaignPlasma) public; function addFeesCollectedInCurrency(string currency, uint amount) public payable; function updateTokensReceivedFromDistributionFees(uint amountOfTokens) public; } contract ITwoKeyCampaignValidator { function isCampaignValidated(address campaign) public view returns (bool); function validateAcquisitionCampaign(address campaign, string nonSingletonHash) public; function validateDonationCampaign(address campaign, address donationConversionHandler, address donationLogicHandler, string nonSingletonHash) public; function validateCPCCampaign(address campaign, string nonSingletonHash) public; } contract ITwoKeyFeeManager { function payDebtWhenConvertingOrWithdrawingProceeds(address _plasmaAddress, uint _debtPaying) public payable; function getDebtForUser(address _userPlasma) public view returns (uint); function payDebtWithDAI(address _plasmaAddress, uint _totalDebt, uint _debtPaid) public; function payDebtWith2Key(address _beneficiaryPublic, address _plasmaAddress, uint _amountOf2keyForRewards) public; function payDebtWith2KeyV2( address _beneficiaryPublic, address _plasmaAddress, uint _amountOf2keyForRewards, address _twoKeyEconomy, address _twoKeyAdmin ) public; function setRegistrationFeeForUser(address _plasmaAddress, uint _registrationFee) public; function addDebtForUser(address _plasmaAddress, uint _debtAmount, string _debtType) public; function withdrawEtherCollected() public returns (uint); function withdraw2KEYCollected() public returns (uint); function withdrawDAICollected(address _dai) public returns (uint); } contract ITwoKeyMaintainersRegistry { function checkIsAddressMaintainer(address _sender) public view returns (bool); function checkIsAddressCoreDev(address _sender) public view returns (bool); function addMaintainers(address [] _maintainers) public; function addCoreDevs(address [] _coreDevs) public; function removeMaintainers(address [] _maintainers) public; function removeCoreDevs(address [] _coreDevs) public; } contract ITwoKeyReg { function addTwoKeyEventSource(address _twoKeyEventSource) public; function changeTwoKeyEventSource(address _twoKeyEventSource) public; function addWhereContractor(address _userAddress, address _contractAddress) public; function addWhereModerator(address _userAddress, address _contractAddress) public; function addWhereReferrer(address _userAddress, address _contractAddress) public; function addWhereConverter(address _userAddress, address _contractAddress) public; function getContractsWhereUserIsContractor(address _userAddress) public view returns (address[]); function getContractsWhereUserIsModerator(address _userAddress) public view returns (address[]); function getContractsWhereUserIsRefferer(address _userAddress) public view returns (address[]); function getContractsWhereUserIsConverter(address _userAddress) public view returns (address[]); function getTwoKeyEventSourceAddress() public view returns (address); function addName(string _name, address _sender, string _fullName, string _email, bytes signature) public; function addNameByUser(string _name) public; function getName2Owner(string _name) public view returns (address); function getOwner2Name(address _sender) public view returns (string); function getPlasmaToEthereum(address plasma) public view returns (address); function getEthereumToPlasma(address ethereum) public view returns (address); function checkIfTwoKeyMaintainerExists(address _maintainer) public view returns (bool); function getUserData(address _user) external view returns (bytes); } contract ITwoKeySingletoneRegistryFetchAddress { function getContractProxyAddress(string _contractName) public view returns (address); function getNonUpgradableContractAddress(string contractName) public view returns (address); function getLatestCampaignApprovedVersion(string campaignType) public view returns (string); } interface ITwoKeySingletonesRegistry { /** * @dev This event will be emitted every time a new proxy is created * @param proxy representing the address of the proxy created */ event ProxyCreated(address proxy); /** * @dev This event will be emitted every time a new implementation is registered * @param version representing the version name of the registered implementation * @param implementation representing the address of the registered implementation * @param contractName is the name of the contract we added new version */ event VersionAdded(string version, address implementation, string contractName); /** * @dev Registers a new version with its implementation address * @param version representing the version name of the new implementation to be registered * @param implementation representing the address of the new implementation to be registered */ function addVersion(string _contractName, string version, address implementation) public; /** * @dev Tells the address of the implementation for a given version * @param _contractName is the name of the contract we're querying * @param version to query the implementation of * @return address of the implementation registered for the given version */ function getVersion(string _contractName, string version) public view returns (address); } contract ITwoKeyEventSourceStorage is IStructuredStorage { } contract ITwoKeySingletonUtils { address public TWO_KEY_SINGLETON_REGISTRY; // Modifier to restrict method calls only to maintainers modifier onlyMaintainer { address twoKeyMaintainersRegistry = getAddressFromTwoKeySingletonRegistry("TwoKeyMaintainersRegistry"); require(ITwoKeyMaintainersRegistry(twoKeyMaintainersRegistry).checkIsAddressMaintainer(msg.sender)); _; } /** * @notice Function to get any singleton contract proxy address from TwoKeySingletonRegistry contract * @param contractName is the name of the contract we're looking for */ function getAddressFromTwoKeySingletonRegistry( string contractName ) internal view returns (address) { return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY) .getContractProxyAddress(contractName); } function getNonUpgradableContractAddressFromTwoKeySingletonRegistry( string contractName ) internal view returns (address) { return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY) .getNonUpgradableContractAddress(contractName); } } contract UpgradeabilityStorage { // Versions registry ITwoKeySingletonesRegistry internal registry; // Address of the current implementation address internal _implementation; /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } } contract Upgradeable is UpgradeabilityStorage { /** * @dev Validates the caller is the versions registry. * @param sender representing the address deploying the initial behavior of the contract */ function initialize(address sender) public payable { require(msg.sender == address(registry)); } } contract TwoKeyEventSource is Upgradeable, ITwoKeySingletonUtils { bool initialized; ITwoKeyEventSourceStorage public PROXY_STORAGE_CONTRACT; string constant _twoKeyCampaignValidator = "TwoKeyCampaignValidator"; string constant _twoKeyFactory = "TwoKeyFactory"; string constant _twoKeyRegistry = "TwoKeyRegistry"; string constant _twoKeyAdmin = "TwoKeyAdmin"; string constant _twoKeyExchangeRateContract = "TwoKeyExchangeRateContract"; string constant _twoKeyMaintainersRegistry = "TwoKeyMaintainersRegistry"; string constant _deepFreezeTokenPool = "TwoKeyDeepFreezeTokenPool"; /** * Modifier which will allow only completely verified and validated contracts to call some functions */ modifier onlyAllowedContracts { address twoKeyCampaignValidator = getAddressFromTwoKeySingletonRegistry(_twoKeyCampaignValidator); require(ITwoKeyCampaignValidator(twoKeyCampaignValidator).isCampaignValidated(msg.sender) == true); _; } /** * Modifier which will allow only TwoKeyCampaignValidator to make some calls */ modifier onlyTwoKeyCampaignValidator { address twoKeyCampaignValidator = getAddressFromTwoKeySingletonRegistry(_twoKeyCampaignValidator); require(msg.sender == twoKeyCampaignValidator); _; } /** * @notice Function to set initial params in the contract * @param _twoKeySingletonesRegistry is the address of TWO_KEY_SINGLETON_REGISTRY contract * @param _proxyStorage is the address of proxy of storage contract */ function setInitialParams( address _twoKeySingletonesRegistry, address _proxyStorage ) external { require(initialized == false); TWO_KEY_SINGLETON_REGISTRY = _twoKeySingletonesRegistry; PROXY_STORAGE_CONTRACT = ITwoKeyEventSourceStorage(_proxyStorage); initialized = true; } /** * Events which will be emitted during use of system * All events are emitted from this contract * Every event is monitored in GraphQL */ event Created( address _campaign, address _owner, address _moderator ); event Joined( address _campaign, address _from, address _to ); event Converted( address _campaign, address _converter, uint256 _amount ); event ConvertedAcquisition( address _campaign, address _converterPlasma, uint256 _baseTokens, uint256 _bonusTokens, uint256 _conversionAmount, bool _isFiatConversion, uint _conversionId ); event ConvertedDonation( address _campaign, address _converterPlasma, uint _conversionAmount, uint _conversionId ); event Rewarded( address _campaign, address _to, uint256 _amount ); event Cancelled( address _campaign, address _converter, uint256 _indexOrAmount ); event Rejected( address _campaign, address _converter ); event UpdatedPublicMetaHash( uint timestamp, string value ); event UpdatedData( uint timestamp, uint value, string action ); event ReceivedEther( address _sender, uint value ); event AcquisitionCampaignCreated( address proxyLogicHandler, address proxyConversionHandler, address proxyAcquisitionCampaign, address proxyPurchasesHandler, address contractor ); event DonationCampaignCreated( address proxyDonationCampaign, address proxyDonationConversionHandler, address proxyDonationLogicHandler, address contractor ); event CPCCampaignCreated( address proxyCPCCampaign, address contractor //Contractor public address ); event PriceUpdated( bytes32 _currency, uint newRate, uint _timestamp, address _updater ); event UserRegistered( string _handle, address _address ); event Executed( address campaignAddress, address converterPlasmaAddress, uint conversionId, uint tokens ); event TokenWithdrawnFromPurchasesHandler( address campaignAddress, uint conversionID, uint tokensAmountWithdrawn ); event Debt ( address plasmaAddress, uint weiAmount, bool addition, //If true means debt increasing otherwise it means that event emitted when user paid part of the debt string currency ); event ReceivedTokensAsModerator( address campaignAddress, uint amountOfTokens ); event ReceivedTokensDeepFreezeTokenPool( address campaignAddress, uint amountOfTokens ); event HandleChanged( address userPlasmaAddress, string newHandle ); event DaiReleased( address contractSenderAddress, uint amountOfDAI ); event RebalancedRatesEvent ( uint priceAtBeginning, uint priceAtRebalancingTime, uint ratio, uint amountOfTokensTransferedInAction, string actionPerformedWithUpgradableExchange ); event EndedBudgetCampaign ( address campaignPlasmaAddress, uint contractorLeftover, uint moderatorEarningsDistributed ); event RebalancedRewards( uint cycleId, uint amountOfTokens, string action ); event UserWithdrawnNetworkEarnings( address user, uint amountOfTokens ); /** * @notice Function to emit created event every time campaign is created * @param _campaign is the address of the deployed campaign * @param _owner is the contractor address of the campaign * @param _moderator is the address of the moderator in campaign * @dev this function updates values in TwoKeyRegistry contract */ function created( address _campaign, address _owner, address _moderator ) external onlyTwoKeyCampaignValidator { emit Created(_campaign, _owner, _moderator); } /** * @notice Function to emit created event every time someone has joined to campaign * @param _campaign is the address of the deployed campaign * @param _from is the address of the referrer * @param _to is the address of person who has joined * @dev this function updates values in TwoKeyRegistry contract */ function joined( address _campaign, address _from, address _to ) external onlyAllowedContracts { emit Joined(_campaign, _from, _to); } /** * @notice Function to emit converted event * @param _campaign is the address of main campaign contract * @param _converter is the address of converter during the conversion * @param _conversionAmount is conversion amount */ function converted( address _campaign, address _converter, uint256 _conversionAmount ) external onlyAllowedContracts { emit Converted(_campaign, _converter, _conversionAmount); } function rejected( address _campaign, address _converter ) external onlyAllowedContracts { emit Rejected(_campaign, _converter); } /** * @notice Function to emit event every time conversion gets executed * @param _campaignAddress is the main campaign contract address * @param _converterPlasmaAddress is the address of converter plasma * @param _conversionId is the ID of conversion, unique per campaign */ function executed( address _campaignAddress, address _converterPlasmaAddress, uint _conversionId, uint tokens ) external onlyAllowedContracts { emit Executed(_campaignAddress, _converterPlasmaAddress, _conversionId, tokens); } /** * @notice Function to emit created event every time conversion happened under AcquisitionCampaign * @param _campaign is the address of the deployed campaign * @param _converterPlasma is the converter address * @param _baseTokens is the amount of tokens bought * @param _bonusTokens is the amount of bonus tokens received * @param _conversionAmount is the amount of conversion * @param _isFiatConversion is flag representing if conversion is either FIAT or ETHER * @param _conversionId is the id of conversion * @dev this function updates values in TwoKeyRegistry contract */ function convertedAcquisition( address _campaign, address _converterPlasma, uint256 _baseTokens, uint256 _bonusTokens, uint256 _conversionAmount, bool _isFiatConversion, uint _conversionId ) external onlyAllowedContracts { emit ConvertedAcquisition( _campaign, _converterPlasma, _baseTokens, _bonusTokens, _conversionAmount, _isFiatConversion, _conversionId ); } /** * @notice Function to emit created event every time conversion happened under DonationCampaign * @param _campaign is the address of main campaign contract * @param _converterPlasma is the address of the converter * @param _conversionAmount is the amount of conversion * @param _conversionId is the id of conversion */ function convertedDonation( address _campaign, address _converterPlasma, uint256 _conversionAmount, uint256 _conversionId ) external onlyAllowedContracts { emit ConvertedDonation( _campaign, _converterPlasma, _conversionAmount, _conversionId ); } /** * @notice Function to emit created event every time bounty is distributed between influencers * @param _campaign is the address of the deployed campaign * @param _to is the reward receiver * @param _amount is the reward amount */ function rewarded( address _campaign, address _to, uint256 _amount ) external onlyAllowedContracts { emit Rewarded(_campaign, _to, _amount); } /** * @notice Function to emit created event every time campaign is cancelled * @param _campaign is the address of the cancelled campaign * @param _converter is the address of the converter * @param _indexOrAmount is the amount of campaign */ function cancelled( address _campaign, address _converter, uint256 _indexOrAmount ) external onlyAllowedContracts { emit Cancelled(_campaign, _converter, _indexOrAmount); } /** * @notice Function to emit event every time someone starts new Acquisition campaign * @param proxyLogicHandler is the address of TwoKeyAcquisitionLogicHandler proxy deployed by TwoKeyFactory * @param proxyConversionHandler is the address of TwoKeyConversionHandler proxy deployed by TwoKeyFactory * @param proxyAcquisitionCampaign is the address of TwoKeyAcquisitionCampaign proxy deployed by TwoKeyFactory * @param proxyPurchasesHandler is the address of TwoKeyPurchasesHandler proxy deployed by TwoKeyFactory */ function acquisitionCampaignCreated( address proxyLogicHandler, address proxyConversionHandler, address proxyAcquisitionCampaign, address proxyPurchasesHandler, address contractor ) external { require(msg.sender == getAddressFromTwoKeySingletonRegistry(_twoKeyFactory)); emit AcquisitionCampaignCreated( proxyLogicHandler, proxyConversionHandler, proxyAcquisitionCampaign, proxyPurchasesHandler, contractor ); } /** * @notice Function to emit event every time someone starts new Donation campaign * @param proxyDonationCampaign is the address of TwoKeyDonationCampaign proxy deployed by TwoKeyFactory * @param proxyDonationConversionHandler is the address of TwoKeyDonationConversionHandler proxy deployed by TwoKeyFactory * @param proxyDonationLogicHandler is the address of TwoKeyDonationLogicHandler proxy deployed by TwoKeyFactory */ function donationCampaignCreated( address proxyDonationCampaign, address proxyDonationConversionHandler, address proxyDonationLogicHandler, address contractor ) external { require(msg.sender == getAddressFromTwoKeySingletonRegistry(_twoKeyFactory)); emit DonationCampaignCreated( proxyDonationCampaign, proxyDonationConversionHandler, proxyDonationLogicHandler, contractor ); } /** * @notice Function to emit event every time someone starts new CPC campaign * @param proxyCPC is the proxy address of CPC campaign * @param contractor is the PUBLIC address of campaign contractor */ function cpcCampaignCreated( address proxyCPC, address contractor ) external { require(msg.sender == getAddressFromTwoKeySingletonRegistry(_twoKeyFactory)); emit CPCCampaignCreated( proxyCPC, contractor ); } /** * @notice Function which will emit event PriceUpdated every time that happens under TwoKeyExchangeRateContract * @param _currency is the hexed string of currency name * @param _newRate is the new rate * @param _timestamp is the time of updating * @param _updater is the maintainer address which performed this call */ function priceUpdated( bytes32 _currency, uint _newRate, uint _timestamp, address _updater ) external { require(msg.sender == getAddressFromTwoKeySingletonRegistry(_twoKeyExchangeRateContract)); emit PriceUpdated(_currency, _newRate, _timestamp, _updater); } /** * @notice Function to emit event every time user is registered * @param _handle is the handle of the user * @param _address is the address of the user */ function userRegistered( string _handle, address _address, uint _registrationFee ) external { require(isAddressMaintainer(msg.sender) == true); ITwoKeyFeeManager(getAddressFromTwoKeySingletonRegistry("TwoKeyFeeManager")).setRegistrationFeeForUser(_address, _registrationFee); emit UserRegistered(_handle, _address); emit Debt(_address, _registrationFee, true, "ETH"); } function addAdditionalDebtForUser( address _plasmaAddress, uint _debtAmount, string _debtType ) public { require(isAddressMaintainer(msg.sender) == true); ITwoKeyFeeManager(getAddressFromTwoKeySingletonRegistry("TwoKeyFeeManager")).addDebtForUser(_plasmaAddress, _debtAmount, _debtType); emit Debt(_plasmaAddress, _debtAmount, true, "ETH"); } /** * @notice Function which will emit every time some debt is increased or paid * @param _plasmaAddress is the address of the user we are increasing/decreasing debt for * @param _amount is the amount of ETH he paid/increased * @param _isAddition is stating either debt increased or paid */ function emitDebtEvent( address _plasmaAddress, uint _amount, bool _isAddition, string _currency ) external { require(msg.sender == getAddressFromTwoKeySingletonRegistry("TwoKeyFeeManager")); emit Debt( _plasmaAddress, _amount, _isAddition, _currency ); } /** * @notice Function which will be called by TwoKeyAdmin every time it receives 2KEY tokens * as a moderator on TwoKeyCampaigns * @param _campaignAddress is the address of the campaign sending tokens * @param _amountOfTokens is the amount of tokens sent */ function emitReceivedTokensAsModerator( address _campaignAddress, uint _amountOfTokens ) public { require(msg.sender == getAddressFromTwoKeySingletonRegistry(_twoKeyAdmin)); emit ReceivedTokensAsModerator( _campaignAddress, _amountOfTokens ); } /** * @notice Function which will be called by TwoKeyDeepFreezeTokenPool every time it receives 2KEY tokens * from moderator rewards on the conversion event * @param _campaignAddress is the address of the campaign sending tokens * @param _amountOfTokens is the amount of tokens sent */ function emitReceivedTokensToDeepFreezeTokenPool( address _campaignAddress, uint _amountOfTokens ) public { require(msg.sender == getAddressFromTwoKeySingletonRegistry(_deepFreezeTokenPool)); emit ReceivedTokensDeepFreezeTokenPool( _campaignAddress, _amountOfTokens ); } /** * @notice Function which will emit an event every time somebody performs * withdraw of bought tokens in AcquisitionCampaign contracts * @param _campaignAddress is the address of main campaign contract * @param _conversionID is the unique ID of conversion inside one campaign * @param _tokensAmountWithdrawn is the amount of tokens user withdrawn */ function tokensWithdrawnFromPurchasesHandler( address _campaignAddress, uint _conversionID, uint _tokensAmountWithdrawn ) external onlyAllowedContracts { emit TokenWithdrawnFromPurchasesHandler(_campaignAddress, _conversionID, _tokensAmountWithdrawn); } function emitRebalancedRatesEvent( uint priceAtBeginning, uint priceAtRebalancingTime, uint ratio, uint amountOfTokensTransferedInAction, string actionPerformedWithUpgradableExchange ) external onlyAllowedContracts { emit RebalancedRatesEvent( priceAtBeginning, priceAtRebalancingTime, ratio, amountOfTokensTransferedInAction, actionPerformedWithUpgradableExchange ); } function emitHandleChangedEvent( address _userPlasmaAddress, string _newHandle ) public { require(msg.sender == getAddressFromTwoKeySingletonRegistry("TwoKeyRegistry")); emit HandleChanged( _userPlasmaAddress, _newHandle ); } /** * @notice Function to emit an event whenever DAI is released as an income * * @param _campaignContractAddress is campaign contract address * @param _amountOfDAI is the amount of DAI being released */ function emitDAIReleasedAsIncome( address _campaignContractAddress, uint _amountOfDAI ) public { require(msg.sender == getAddressFromTwoKeySingletonRegistry("TwoKeyUpgradableExchange")); emit DaiReleased( _campaignContractAddress, _amountOfDAI ); } function emitEndedBudgetCampaign( address campaignPlasmaAddress, uint contractorLeftover, uint moderatorEarningsDistributed ) public { require (msg.sender == getAddressFromTwoKeySingletonRegistry("TwoKeyBudgetCampaignsPaymentsHandler")); emit EndedBudgetCampaign( campaignPlasmaAddress, contractorLeftover, moderatorEarningsDistributed ); } function emitRebalancedRewards( uint cycleId, uint difference, string action ) public { require (msg.sender == getAddressFromTwoKeySingletonRegistry("TwoKeyBudgetCampaignsPaymentsHandler")); emit RebalancedRewards( cycleId, difference, action ); } /** * @notice Function which will emit event that user have withdrawn network earnings * @param user is the address of the user * @param amountOfTokens is the amount of tokens user withdrawn as network earnings */ function emitUserWithdrawnNetworkEarnings( address user, uint amountOfTokens ) public { require(msg.sender == getAddressFromTwoKeySingletonRegistry("TwoKeyParticipationMiningPool")); emit UserWithdrawnNetworkEarnings( user, amountOfTokens ); } /** * @notice Function to check adequate plasma address for submitted eth address * @param me is the ethereum address we request corresponding plasma address for */ function plasmaOf( address me ) public view returns (address) { address twoKeyRegistry = getAddressFromTwoKeySingletonRegistry(_twoKeyRegistry); address plasma = ITwoKeyReg(twoKeyRegistry).getEthereumToPlasma(me); if (plasma != address(0)) { return plasma; } return me; } /** * @notice Function to determine ethereum address of plasma address * @param me is the plasma address of the user * @return ethereum address */ function ethereumOf( address me ) public view returns (address) { address twoKeyRegistry = getAddressFromTwoKeySingletonRegistry(_twoKeyRegistry); address ethereum = ITwoKeyReg(twoKeyRegistry).getPlasmaToEthereum(me); if (ethereum != address(0)) { return ethereum; } return me; } /** * @notice Address to check if an address is maintainer in TwoKeyMaintainersRegistry * @param _maintainer is the address we're checking this for */ function isAddressMaintainer( address _maintainer ) public view returns (bool) { address twoKeyMaintainersRegistry = getAddressFromTwoKeySingletonRegistry(_twoKeyMaintainersRegistry); bool _isMaintainer = ITwoKeyMaintainersRegistry(twoKeyMaintainersRegistry).checkIsAddressMaintainer(_maintainer); return _isMaintainer; } /** * @notice In default TwoKeyAdmin will be moderator and his fee percentage per conversion is predefined */ function getTwoKeyDefaultIntegratorFeeFromAdmin() public view returns (uint) { address twoKeyAdmin = getAddressFromTwoKeySingletonRegistry(_twoKeyAdmin); uint integratorFeePercentage = ITwoKeyAdmin(twoKeyAdmin).getDefaultIntegratorFeePercent(); return integratorFeePercentage; } /** * @notice Function to get default network tax percentage */ function getTwoKeyDefaultNetworkTaxPercent() public view returns (uint) { address twoKeyAdmin = getAddressFromTwoKeySingletonRegistry(_twoKeyAdmin); uint networkTaxPercent = ITwoKeyAdmin(twoKeyAdmin).getDefaultNetworkTaxPercent(); return networkTaxPercent; } }
* @notice Function to emit created event every time campaign is cancelled @param _campaign is the address of the cancelled campaign @param _converter is the address of the converter @param _indexOrAmount is the amount of campaign/
function cancelled( address _campaign, address _converter, uint256 _indexOrAmount ) external onlyAllowedContracts { emit Cancelled(_campaign, _converter, _indexOrAmount); }
10,197,602
[ 1, 2083, 358, 3626, 2522, 871, 3614, 813, 8965, 353, 13927, 225, 389, 14608, 353, 326, 1758, 434, 326, 13927, 8965, 225, 389, 15747, 353, 326, 1758, 434, 326, 6027, 225, 389, 1615, 1162, 6275, 353, 326, 3844, 434, 8965, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13927, 12, 203, 3639, 1758, 225, 389, 14608, 16, 203, 3639, 1758, 389, 15747, 16, 203, 3639, 2254, 5034, 389, 1615, 1162, 6275, 203, 565, 262, 203, 565, 3903, 203, 565, 1338, 5042, 20723, 203, 565, 288, 203, 3639, 3626, 10347, 1259, 24899, 14608, 16, 389, 15747, 16, 389, 1615, 1162, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xFe244Bbd340cbA81F4106F2B0B936453D1B1E2B6/sources/project_/contracts/superfluid/SuperfluidPool.sol
@dev Transfers `amount` units from `from` to `to` if allowed - amount is negative, this reverts due to overflow
function transferFrom(address from, address to, uint256 amount) external override returns (bool) { uint256 allowed = _allowances[from][msg.sender]; if (allowed != type(uint256).max) _allowances[from][msg.sender] = allowed - amount; _transfer(from, to, amount); return true; }
841,413
[ 1, 1429, 18881, 1375, 8949, 68, 4971, 628, 1375, 2080, 68, 358, 1375, 869, 68, 309, 2935, 300, 3844, 353, 6092, 16, 333, 15226, 87, 6541, 358, 9391, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 3903, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 2935, 273, 389, 5965, 6872, 63, 2080, 6362, 3576, 18, 15330, 15533, 203, 203, 3639, 309, 261, 8151, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 389, 5965, 6872, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 300, 3844, 31, 203, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Base64.sol"; contract Loot is ERC721Enumerable, ReentrancyGuard, Ownable { string[] private weapons = [ "Warhammer", "Quarterstaff", "Maul", "Mace", "Club", "Katana", "Falchion", "Scimitar", "Long Sword", "Short Sword", "Ghost Wand", "Grave Wand", "Bone Wand", "Wand", "Grimoire", "Chronicle", "Tome", "Book" ]; string[] private chestArmor = [ "Divine Robe", "Silk Robe", "Linen Robe", "Robe", "Shirt", "Demon Husk", "Dragonskin Armor", "Studded Leather Armor", "Hard Leather Armor", "Leather Armor", "Holy Chestplate", "Ornate Chestplate", "Plate Mail", "Chain Mail", "Ring Mail" ]; string[] private headArmor = [ "Ancient Helm", "Ornate Helm", "Great Helm", "Full Helm", "Helm", "Demon Crown", "Dragon's Crown", "War Cap", "Leather Cap", "Cap", "Crown", "Divine Hood", "Silk Hood", "Linen Hood", "Hood" ]; string[] private waistArmor = [ "Ornate Belt", "War Belt", "Plated Belt", "Mesh Belt", "Heavy Belt", "Demonhide Belt", "Dragonskin Belt", "Studded Leather Belt", "Hard Leather Belt", "Leather Belt", "Brightsilk Sash", "Silk Sash", "Wool Sash", "Linen Sash", "Sash" ]; string[] private footArmor = [ "Holy Greaves", "Ornate Greaves", "Greaves", "Chain Boots", "Heavy Boots", "Demonhide Boots", "Dragonskin Boots", "Studded Leather Boots", "Hard Leather Boots", "Leather Boots", "Divine Slippers", "Silk Slippers", "Wool Shoes", "Linen Shoes", "Shoes" ]; string[] private handArmor = [ "Holy Gauntlets", "Ornate Gauntlets", "Gauntlets", "Chain Gloves", "Heavy Gloves", "Demon's Hands", "Dragonskin Gloves", "Studded Leather Gloves", "Hard Leather Gloves", "Leather Gloves", "Divine Gloves", "Silk Gloves", "Wool Gloves", "Linen Gloves", "Gloves" ]; string[] private necklaces = [ "Necklace", "Amulet", "Pendant" ]; string[] private rings = [ "Gold Ring", "Silver Ring", "Bronze Ring", "Platinum Ring", "Titanium Ring" ]; string[] private suffixes = [ "of Power", "of Giants", "of Titans", "of Skill", "of Perfection", "of Brilliance", "of Enlightenment", "of Protection", "of Anger", "of Rage", "of Fury", "of Vitriol", "of the Fox", "of Detection", "of Reflection", "of the Twins" ]; string[] private namePrefixes = [ "Agony", "Apocalypse", "Armageddon", "Beast", "Behemoth", "Blight", "Blood", "Bramble", "Brimstone", "Brood", "Carrion", "Cataclysm", "Chimeric", "Corpse", "Corruption", "Damnation", "Death", "Demon", "Dire", "Dragon", "Dread", "Doom", "Dusk", "Eagle", "Empyrean", "Fate", "Foe", "Gale", "Ghoul", "Gloom", "Glyph", "Golem", "Grim", "Hate", "Havoc", "Honour", "Horror", "Hypnotic", "Kraken", "Loath", "Maelstrom", "Mind", "Miracle", "Morbid", "Oblivion", "Onslaught", "Pain", "Pandemonium", "Phoenix", "Plague", "Rage", "Rapture", "Rune", "Skull", "Sol", "Soul", "Sorrow", "Spirit", "Storm", "Tempest", "Torment", "Vengeance", "Victory", "Viper", "Vortex", "Woe", "Wrath", "Light's", "Shimmering" ]; string[] private nameSuffixes = [ "Bane", "Root", "Bite", "Song", "Roar", "Grasp", "Instrument", "Glow", "Bender", "Shadow", "Whisper", "Shout", "Growl", "Tear", "Peak", "Form", "Sun", "Moon" ]; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getWeapon(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "WEAPON", weapons); } function getChest(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "CHEST", chestArmor); } function getHead(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "HEAD", headArmor); } function getWaist(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "WAIST", waistArmor); } function getFoot(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "FOOT", footArmor); } function getHand(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "HAND", handArmor); } function getNeck(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "NECK", necklaces); } function getRing(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "RING", rings); } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; uint256 greatness = rand % 21; if (greatness > 14) { output = string(abi.encodePacked(output, " ", suffixes[rand % suffixes.length])); } if (greatness >= 19) { string[2] memory name; name[0] = namePrefixes[rand % namePrefixes.length]; name[1] = nameSuffixes[rand % nameSuffixes.length]; if (greatness == 19) { output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output)); } else { output = string(abi.encodePacked('"', name[0], ' ', name[1], '" ', output, " +1")); } } return output; } function tokenURI(uint256 tokenId) override public view returns (string memory) { string[17] memory parts; parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">'; parts[1] = getWeapon(tokenId); parts[2] = '</text><text x="10" y="40" class="base">'; parts[3] = getChest(tokenId); parts[4] = '</text><text x="10" y="60" class="base">'; parts[5] = getHead(tokenId); parts[6] = '</text><text x="10" y="80" class="base">'; parts[7] = getWaist(tokenId); parts[8] = '</text><text x="10" y="100" class="base">'; parts[9] = getFoot(tokenId); parts[10] = '</text><text x="10" y="120" class="base">'; parts[11] = getHand(tokenId); parts[12] = '</text><text x="10" y="140" class="base">'; parts[13] = getNeck(tokenId); parts[14] = '</text><text x="10" y="160" class="base">'; parts[15] = getRing(tokenId); parts[16] = '</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16])); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Bag #', toString(tokenId), '", "description": "Loot is randomized adventurer gear generated and stored on chain. Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Loot in any way you want.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } function claimLots(uint256 tokenId,uint256 ammount) public nonReentrant { require(tokenId > 0 && tokenId < (7778-ammount), "Token ID invalid"); while (ammount != 0) { _safeMint(_msgSender(), tokenId); tokenId++; ammount--; } } function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 7777 && tokenId < 8001, "Token ID invalid"); _safeMint(owner(), tokenId); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } constructor() ERC721("Loot", "LOOT") Ownable() {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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.0 (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.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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.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); } } } } // SPDX-License-Identifier: MIT // 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; } } // SPDX-License-Identifier: MIT // 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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.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); } // SPDX-License-Identifier: NONE pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./Relic.sol"; contract ExampleRelicMinter is IRelicMinter, Ownable { Relic private _relic; uint256 private _minTokenId; uint256 private _maxTokenId; uint256 private _nextTokenId; string public placeholderImageURL; // this is used when images are not yet pinned string public imageBaseURL; constructor( Relic relic, uint256 minTokenId, uint256 maxTokenId, string memory placeholderImgURL, string memory imgBaseURL) { _relic = relic; _minTokenId = minTokenId; _maxTokenId = maxTokenId; _nextTokenId = minTokenId; placeholderImageURL = placeholderImgURL; imageBaseURL = imgBaseURL; } function setPlaceholderImageURL(string memory newPlaceholderImageURL) public onlyOwner { placeholderImageURL = newPlaceholderImageURL; } function setImageBaseURL(string memory newImageBaseURL) public onlyOwner { imageBaseURL = newImageBaseURL; } function mintTokenId(uint256 tokenId, bytes12 data) public { _relic.mint(_msgSender(), tokenId, data); } function mint(bytes12 data) public { while (_relic.exists(_nextTokenId)) { ++_nextTokenId; } require(_nextTokenId <= _maxTokenId, "run out of relics"); mintTokenId(_nextTokenId++, data); } function getTokenOrderIndex(uint256 /*tokenId*/, bytes12 /*data*/) external override pure returns(uint) { return 0; } function getTokenProvenance(uint256 /*tokenId*/, bytes12 /*data*/) external override pure returns(string memory) { return "Example Chapter"; } function getAdditionalAttributes(uint256 /*tokenId*/, bytes12 /*data*/) external override pure returns(string memory) { return ",{\"trait_type\": \"Extra1\", \"value\": \"Thing1\"}" ",{\"trait_type\": \"Extra2\", \"value\": \"Thing2\"}"; } function getImageBaseURL() external override view returns(string memory) { if (bytes(imageBaseURL).length > 0) { return imageBaseURL; } return placeholderImageURL; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1967/ERC1967ProxyImplementation.sol"; import "./OpenSea/ERC721TradableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; struct RelicProperties { uint256 relicTypeId; uint256 materialId; uint256 materialOffset; // this relic's number relative to material, e.g. Gold Skull #42 uint256 poleId; uint256 astralId; uint256 elementId; uint256 alignmentId; uint256 greatness; } interface IRelicMinter { // The relic minter can inject attributes into the metadata attributes array, // they will be added after the standard ones so should begin with a comma. // e.g. ,{"trait_type": "Extra Field", "value": "The Value"} function getAdditionalAttributes(uint256 tokenId, bytes12 data) external view returns(string memory); function getTokenOrderIndex(uint256 tokenId, bytes12 data) external view returns(uint); function getTokenProvenance(uint256 tokenId, bytes12 data) external view returns(string memory); function getImageBaseURL() external view returns(string memory); } contract Relic is ProxyImplementation, ERC721TradableUpgradeable { mapping(address => bool) private _whitelistedMinters; mapping(uint256 => uint256) public _tokenMintInfo; string public _placeholderImageURL; string public _animationBaseURL; string public _collectionName; string public _collectionDesc; string public _collectionImgURL; string public _collectionExtURL; uint256 public _feeBasisPoints; address public _feeRecipient; function init( string memory name, string memory symbol, address proxyRegistryAddress, string memory placeholderImageURL, string memory animationBaseURL, string memory collectionName, string memory collectionDesc, string memory collectionImgURL, string memory collectionExtURL, uint256 feeBasisPoints, address feeRecipient) public onlyOwner initializer { _initializeEIP712(name); __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721TradableUpgradeable_init_unchained(proxyRegistryAddress); _placeholderImageURL = placeholderImageURL; _animationBaseURL = animationBaseURL; _collectionName = collectionName; _collectionDesc = collectionDesc; _collectionImgURL = collectionImgURL; _collectionExtURL = collectionExtURL; _feeBasisPoints = feeBasisPoints; _feeRecipient = feeRecipient; } function exists(uint256 tokenId) public view returns(bool) { return _exists(tokenId); } function mint(address to, uint256 tokenId, bytes12 data) public { require(isMinterWhitelisted(_msgSender()), "minter not whitelisted"); // only need 20 bytes for the minter address, so might as well use the // other 12 bytes of the slot for something. The minter can pass // whatever they want, I'm thinking some kind of useful context, e.g. a // minter which manages multiple dungeons could use this field for // dungeon Id _tokenMintInfo[tokenId] = packTokenMintInfo(IRelicMinter(_msgSender()), data); _safeMint(to, tokenId); } function tokenURI(uint256 tokenId) public override view returns (string memory) { require(_exists(tokenId), "token doesn't exist"); RelicProperties memory relicProps = getRelicProperties(tokenId); (IRelicMinter relicMinter, bytes12 data) = unpackTokenMintInfo(_tokenMintInfo[tokenId]); uint orderIndex = relicMinter.getTokenOrderIndex(tokenId, data); string memory provenance = relicMinter.getTokenProvenance(tokenId, data); string memory baseImageURL = relicMinter.getImageBaseURL(); if (bytes(baseImageURL).length == 0) { baseImageURL = _placeholderImageURL; } string memory imageURL = getImageURLForToken(tokenId, baseImageURL, orderIndex, provenance); string memory attrs = string(abi.encodePacked( _getAttributes(relicProps), ",{\"trait_type\": \"Order\", \"value\": \"", getOrderSuffix(orderIndex), "\"}", ",{\"trait_type\": \"Provenance\", \"value\": \"", provenance, "\"}", relicMinter.getAdditionalAttributes(tokenId, data) )); return string(abi.encodePacked( "data:application/json;utf8,{" "\"name\": \"", getName(relicProps.relicTypeId, relicProps.materialId, relicProps.materialOffset), "\"," "\"description\": \"Loot dungeon relic\"," "\"image\": \"", imageURL, "\",", "\"external_url\": \"", imageURL,"\",", // TODO: this should be link to asset on TheCrupt "\"attributes\": [", attrs, "]}" )); } function contractURI() public view returns(string memory) { return string(abi.encodePacked( "data:application/json;utf8,{" "\"name\": \"", _collectionName, "\"," "\"description\": \"", _collectionDesc, "\"," "\"image\": \"", _collectionImgURL, "\",", "\"external_link\": \"", _collectionExtURL,"\",", "\"seller_fee_basis_points\": \"", StringsUpgradeable.toString(_feeBasisPoints),"\",", "\"fee_recipient\": \"", StringsUpgradeable.toHexString(uint256(uint160(_feeRecipient)), 20),"\"", "}" )); } function getRelicProperties(uint256 tokenId) public pure returns(RelicProperties memory) { RelicProperties memory props; uint256 relicsPerMaterialForCurrentType = 84; uint256 totalRelicsOfCurrentType; uint256 tokenIdStartForCurrentType; uint256 tokenIdEndForCurrentType; // exclusive while (true) { totalRelicsOfCurrentType = relicsPerMaterialForCurrentType << 2; tokenIdEndForCurrentType = tokenIdStartForCurrentType + totalRelicsOfCurrentType; if (tokenId < tokenIdEndForCurrentType) { break; } ++props.relicTypeId; tokenIdStartForCurrentType = tokenIdEndForCurrentType; relicsPerMaterialForCurrentType <<= 1; } // find out the offset of this token Id into its relic type, that is to // say if it's the Nth Skull, what is the value of N uint256 relicOffset = tokenId - tokenIdStartForCurrentType; // we want materials to be allocated in order from smallest to largest // token Id, so derive material from relic offset props.materialId = relicOffset / relicsPerMaterialForCurrentType; // we want to know that this is the Nth relic of type x material y, for // the token name e.g. Golden Skull #42 props.materialOffset = relicOffset % relicsPerMaterialForCurrentType; // First relic of each material set is greatness 20 then it is decremented per token until it loops at the minimum for its type uint256 minGreatness = getMiniumGreatness(props.relicTypeId); uint256 greatnessRange = 21 - minGreatness; props.greatness = 20 - (props.materialOffset % greatnessRange); // offset the attributes Id with a "random" number per relic + material // combination, so that all relics of a certain material don't start on // N Sun Earth Good Greatness 0 etc uint256 attributesId = relicOffset + uint256(keccak256(abi.encodePacked(props.relicTypeId, props.materialId))); props.alignmentId = (attributesId / greatnessRange) & 3; props.elementId = (attributesId / (greatnessRange * 4)) & 3; props.astralId = (attributesId / (greatnessRange * 16)) & 3; props.poleId = (attributesId / (greatnessRange * 64)) & 3; return props; } function packTokenMintInfo(IRelicMinter relicMinter, bytes12 data) public pure returns(uint256) { return (uint256(uint160(address(relicMinter))) << 96) | uint96(data); } function unpackTokenMintInfo(uint256 mintInfo) public pure returns(IRelicMinter relicMinter, bytes12 data) { relicMinter = IRelicMinter(address(uint160(mintInfo >> 96))); data = bytes12(uint96(mintInfo & 0xffffffffffffffffffffffff)); } function getRelicType(uint256 relicId) public pure returns(string memory) { string[7] memory relics = ["Skull", "Crown", "Medal", "Key", "Dagger", "Gem", "Coin"]; return relics[relicId]; } function getMaterial(uint256 materialId) public pure returns(string memory) { string[4] memory materials = ["Gold", "Ice", "Fire", "Jade"]; return materials[materialId]; } function getName(uint256 relicId, uint256 materialId, uint256 materialOffset) public pure returns(string memory) { return string(abi.encodePacked( getMaterial(materialId), " ", getRelicType(relicId), " #", StringsUpgradeable.toString(materialOffset + 1))); } function getAlignment(uint256 alignmentId) public pure returns(string memory) { string[4] memory alignment = ["Good", "Evil", "Lawful", "Chaos"]; return alignment[alignmentId]; } function getElement(uint256 elementId) public pure returns(string memory) { string[4] memory element = ["Earth", "Wind", "Fire", "Water"]; return element[elementId]; } function getAstral(uint256 astralId) public pure returns(string memory) { string[4] memory astral = ["Earth", "Sun", "Moon", "Stars"]; return astral[astralId]; } function getPole(uint256 poleId) public pure returns(string memory) { string[4] memory pole = ["North", "South", "East", "West"]; return pole[poleId]; } function getMiniumGreatness(uint256 relicId) public pure returns(uint256) { uint256[7] memory greatnesses = [(uint256)(20), 19, 18,17,15,10,0]; return greatnesses[relicId]; } function getOrderSuffix(uint orderId) public pure returns(string memory) { string[16] memory suffixes = [ "of Power", "of Giants", "of Titans", "of Skill", "of Perfection", "of Brilliance", "of Enlightenment", "of Protection", "of Anger", "of Rage", "of Fury", "of Vitriol", "of the Fox", "of Detection", "of Reflection", "of the Twins" ]; return suffixes[orderId]; } // encodes properties in relicProps for use in a URL, such as for animation_url function _getURLParams(RelicProperties memory relicProps) public pure returns(string memory) { return string(abi.encodePacked( "relicType=", getRelicType(relicProps.relicTypeId), "&material=", getMaterial(relicProps.materialId), "&pole=", getPole(relicProps.poleId), "&astral=", getAstral(relicProps.astralId), "&element=", getElement(relicProps.elementId), "&alignment=", getAlignment(relicProps.alignmentId), "&greatness=", StringsUpgradeable.toString(relicProps.greatness) )); } // encodes properties in relicProps for use in the attributes array of token // metadata function _getAttributes(RelicProperties memory relicProps) public pure returns(string memory) { bytes memory str = abi.encodePacked( "{\"trait_type\": \"Relic Type\", \"value\": \"", getRelicType(relicProps.relicTypeId),"\"}," "{\"trait_type\": \"Material\", \"value\": \"", getMaterial(relicProps.materialId),"\"}," "{\"trait_type\": \"Pole\", \"value\": \"", getPole(relicProps.poleId),"\"}," "{\"trait_type\": \"Astral\", \"value\": \"", getAstral(relicProps.astralId),"\"}," "{\"trait_type\": \"Element\", \"value\": \"", getElement(relicProps.elementId),"\"}," "{\"trait_type\": \"Alignment\", \"value\": \"", getAlignment(relicProps.alignmentId),"\"}," ); // had to break this into two calls to encodePacked as it runs out of stack otherwise str = abi.encodePacked(str, "{\"trait_type\": \"Greatness\", \"value\": \"", StringsUpgradeable.toString(relicProps.greatness),"\"}"); return string(str); } function getImageURLPart1(RelicProperties memory props) internal pure returns(string memory) { return string(abi.encodePacked( Strings.toString(props.materialId), "-", Strings.toString(props.relicTypeId), "-" )); } function getImageURLPart2(RelicProperties memory props) internal pure returns(string memory) { return string(abi.encodePacked( Strings.toString(props.astralId), "-", Strings.toString(props.elementId), "-", Strings.toString(props.poleId), "-" )); } function getImageURLPart3(RelicProperties memory props) internal pure returns(string memory) { return string(abi.encodePacked( Strings.toString(props.alignmentId), "-", Strings.toString(props.greatness), "-" )); } function getImageURLForToken(uint256 tokenId, string memory baseURL, uint orderIndex, string memory provenance) internal pure returns(string memory) { RelicProperties memory props = getRelicProperties(tokenId); return string(abi.encodePacked( baseURL, getImageURLPart1(props), Strings.toString(orderIndex), "-", getImageURLPart2(props), getImageURLPart3(props), provenance, ".png" )); } function isMinterWhitelisted(address minter) public view returns(bool) { return _whitelistedMinters[minter]; } function addWhitelistedMinter(address minter) public onlyOwner { require(AddressUpgradeable.isContract(minter), "minter is not a contract"); require(!isMinterWhitelisted(minter), "already whitelisted"); _whitelistedMinters[minter] = true; } function removeWhitelistedMinter(address minter) public onlyOwner { require(isMinterWhitelisted(minter), "not whitelisted"); _whitelistedMinters[minter] = false; } function setPlaceholderImageURL(string memory placeholderImageURL) public onlyOwner { _placeholderImageURL = placeholderImageURL; } function setAnimationBaseURL(string memory animationBaseURL) public onlyOwner { _animationBaseURL = animationBaseURL; } function setCollectionName(string memory collectionName) public onlyOwner { _collectionName = collectionName; } function setCollectionDesc(string memory collectionDesc) public onlyOwner { _collectionDesc = collectionDesc; } function setCollectionImgURL(string memory collectionImgURL) public onlyOwner { _collectionImgURL = collectionImgURL; } function setCollectionExtURL(string memory collectionExtURL) public onlyOwner { _collectionExtURL = collectionExtURL; } function setFeeBasisPoints(uint256 feeBasisPoints) public onlyOwner { _feeBasisPoints = feeBasisPoints; } function setFeeRecipient(address feeRecipient) public onlyOwner { _feeRecipient = feeRecipient; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./ERC1967Proxy.sol"; contract ProxyImplementation is Initializable { bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; modifier onlyAdmin() { require(admin() == msg.sender, "Implementation: caller is not admin"); _; } modifier onlyOwner() { require(owner() == msg.sender, "Implementation: caller is not owner"); _; } function getImplementation() public view returns(address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } function setImplementation(address implementation) public virtual onlyAdmin { require(AddressUpgradeable.isContract(implementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = implementation; } function admin() public view returns(address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } function owner() public view returns(address) { return admin(); } function setAdmin(address newAdmin) public virtual onlyAdmin { require(newAdmin != address(0), "invalid newAdmin address"); _setAdmin(newAdmin); } function renounceAdminPowers() public virtual onlyAdmin { _setAdmin(address(0)); } function _setAdmin(address newAdmin) private { StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "./ContextMixin.sol"; import "./NativeMetaTransactionUpgradeable.sol"; 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 ERC721TradableUpgradeable is ContextMixin, ERC721Upgradeable, NativeMetaTransactionUpgradeable { using SafeMathUpgradeable for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; function __ERC721TradableUpgradeable_init_unchained(address _proxyRegistryAddress) internal initializer { proxyRegistryAddress = _proxyRegistryAddress; } /** * 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(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol"; contract Proxy { bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; constructor(address implementation) { StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = implementation; StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = msg.sender; } fallback() external payable { _fallback(); } receive() external payable { _fallback(); } function _fallback() private { address implementation = StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; // from OpenZeppelin/contracts assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMathUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import {EIP712BaseUpgradeable} from "./EIP712BaseUpgradeable.sol"; contract NativeMetaTransactionUpgradeable is EIP712BaseUpgradeable { using SafeMathUpgradeable for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal 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 // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract EIP712BaseUpgradeable is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./ContextMixin.sol"; import "./NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract ERC721Tradable is ERC721, ContextMixin, NativeMetaTransaction { address _proxyRegistry; constructor(string memory name, string memory symbol, address proxyRegistry) ERC721(name, symbol) { _proxyRegistry = proxyRegistry; _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) { if (_proxyRegistry != address(0)) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistry); 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 virtual override view returns (address sender) { return ContextMixin.msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./LootClassification.sol"; import "./Relic.sol"; import "hardhat/console.sol"; interface Loot { function ownerOf(uint256 tokenId) external view returns (address); } contract Dungeon is Ownable, IRelicMinter { uint256[] public _dungeons; uint256[] public _relicAwardsByDungeonRank; uint256 _nextDungeonCompleteRank; mapping(uint256 => uint256) _raids; // maps tokenId -> packed raid data function packRaid(uint256 dungeonId, uint256 rewardFirstId, uint256 rewardCount) private pure returns(uint256) { return 1 | (dungeonId << 8) | (rewardFirstId << 16) | (rewardCount << 24); } function unpackRaid(uint256 packed) private pure returns(uint256 dungeonId, uint256 rewardFirstId, uint256 rewardCount) { dungeonId = (packed >> 8) & 0xff; rewardFirstId = (packed >> 16) & 0xff; rewardCount = (packed >> 24) & 0xff; } function packDungeon(uint256 rank, uint256[8] memory hitPoints, uint256 maxHitPoints) private pure returns(uint256) { return rank | (hitPoints[0] << 8) | (hitPoints[1] << 16) | (hitPoints[2] << 24) | (hitPoints[3] << 32) | (hitPoints[4] << 40) | (hitPoints[5] << 48) | (hitPoints[6] << 56) | (hitPoints[7] << 64) | (maxHitPoints << 72); } function unpackDungeon(uint256 packed) private pure returns(uint256 rank, uint256[8] memory hitPoints, uint256 maxHitPoints) { rank = packed & 0xff; hitPoints[0] = (packed >> 8) & 0xff; hitPoints[1] = (packed >> 16) & 0xff; hitPoints[2] = (packed >> 24) & 0xff; hitPoints[3] = (packed >> 32) & 0xff; hitPoints[4] = (packed >> 40) & 0xff; hitPoints[5] = (packed >> 48) & 0xff; hitPoints[6] = (packed >> 56) & 0xff; hitPoints[7] = (packed >> 64) & 0xff; maxHitPoints = (packed >> 72) & 0xff; } Loot internal _loot; LootClassification internal _lootClassification; Relic internal _relic; string constant _EnemiesTag = "ENEMIES"; uint256 constant ENEMY_COUNT = 18; string[] private _enemies = [ // vulnerable to Warriors "Orcs", "Giant Spiders", "Trolls", "Zombies", "Giant Rats", // vulnerable to Hunters "Minotaurs", "Werewolves", "Berserkers", "Goblins", "Gnomes", // vulnerable to Mages (wands) "Ghouls", "Wraiths", "Skeletons", "Revenants", // vulnerable to Mages (books) "Necromancers", "Warlocks", "Wizards", "Druids" ]; string constant _TrapsTag = "TRAPS"; uint256 constant TRAP_COUNT = 15; string[] private _traps = [ // vulnerable to Mages "Trap Doors", "Poison Darts", "Flame Jets", "Poisoned Well", "Falling Net", // vulnerable to Hunters "Blinding Light", "Lightning Bolts", "Pendulum Blades", "Snake Pits", "Poisonous Gas", // vulnerable to Warrirors "Lava Pits", "Burning Oil", "Fire-Breathing Gargoyle", "Hidden Arrows", "Spiked Pits" ]; string constant _MonsterTag = "MONSTERS"; uint256 constant MONSTER_COUNT = 15; string[] private _bossMonsters = [ // vulnerable to Warrirors "Golden Dragon", "Black Dragon", "Bronze Dragon", "Red Dragon", "Wyvern", // vulnerable to Hunters "Fire Giant", "Storm Giant", "Ice Giant", "Frost Giant", "Hill Giant", // vulnerable to Mages "Ogre", "Skeleton Lords", "Knights of Chaos", "Lizard Kings", "Medusa" ]; string constant _ArtefactTag = "ARTEFACTS"; uint256 constant ARTEFACT_COUNT = 15; string[] private _artefacts = [ // vulnerable to Warrirors "The Purple Orb of Zhang", "The Horn of Calling", "The Wondrous Twine of Ping", "The Circle of Squares", "The Scroll of Serpents", // vulnerable to Hunters "The Rod of Runes", "Crystal of Crimson Light", "Oil of Darkness", "Bonecrusher Bag", "Mirror of Madness", // vulnerable to Mages "Ankh of the Ancients", "The Wand of Fear", "The Tentacles of Terror", "The Altar of Ice", "The Creeping Hand" ]; string constant _PassagewaysTag = "PASSAGEWAYS"; uint256 constant PASSAGEWAYS_COUNT = 15; string[] private _passageways = [ // vulnerable to Warrirors "Crushing Walls", "Loose Logs", "Rolling Rocks", "Spiked Floor", "Burning Coals", // vulnerable to Hunters "The Hidden Pit of Doom", "The Sticky Stairs", "The Bridge of Sorrow", "The Maze of Madness", "The Flooded Tunnel", // vulnerable to Mages "The Floor of Fog", "The Frozen Floor", "The Shifting Sands", "The Trembling Trap", "The Broken Glass Floor" ]; string constant _RoomsTag = "ROOMS"; uint256 constant ROOM_COUNT = 15; string[] private _rooms = [ // vulnerable to Warrirors "Room of Undead Hands", "Room of the Stone Claws", "Room of Poison Arrows", "Room of the Iron Bear", "Room of the Wandering Worm", // vulnerable to Hunters "Room of the Infernal Beast", "Room of the Infected Slime", "Room of the Horned Rats", "Room of the Flaming Hounds", "Room of the Million Maggots", // vulnerable to Mages "Room of the Flaming Pits", "Room of the Rabid Flesh Eaters", "Room of the Grim Golem", "Room of the Chaos Firebreathers", "Room of the Nightmare Clones" ]; string constant _TheSoullessTag = "SOULLESS"; uint256 constant SOULLESS_COUNT = 3; string[] private _theSoulless = [ "Lich Queen", "Zombie Lord", "The Grim Reaper" ]; string constant _DemiGodTag = "ELEMENTS"; uint256 constant DEMIGOD_COUNT = 5; string[] private _demiGods = [ "The Bone Demon", "The Snake God", "The Howling Banshee", "Demonspawn", "The Elementals" ]; function numDungeons() public view returns(uint256) { return _dungeons.length; } function getTraitIndex(uint256 dungeonId, string memory traitName, uint256 traitCount) private pure returns (uint256) { return pluckDungeonTrait(dungeonId, traitName, traitCount); } function getTraitName(uint256 dungeonId, string memory traitName, string[] storage traitList) private view returns (string memory) { uint256 index = getTraitIndex(dungeonId, traitName, traitList.length); return traitList[index]; } function enemiesIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _EnemiesTag, ENEMY_COUNT); } function trapsIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _TrapsTag, TRAP_COUNT); } function monsterIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _MonsterTag, MONSTER_COUNT); } function artefactsIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _ArtefactTag, ARTEFACT_COUNT); } function passagewaysIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _PassagewaysTag, PASSAGEWAYS_COUNT); } function roomsIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _RoomsTag, ROOM_COUNT); } function soullessIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _TheSoullessTag, SOULLESS_COUNT); } function demiGodIndex(uint256 dungeonId) private pure returns (uint256) { return getTraitIndex(dungeonId, _DemiGodTag, DEMIGOD_COUNT); } function getEnemies(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _EnemiesTag, _enemies); } function getTraps(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _TrapsTag, _traps); } function getBossMonster(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _MonsterTag, _bossMonsters); } function getArtefact(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _ArtefactTag, _artefacts); } function getPassageways(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _PassagewaysTag, _passageways); } function getRooms(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _RoomsTag, _rooms); } function getTheSoulless(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _TheSoullessTag, _theSoulless); } function getDemiGod(uint256 dungeonId) public view returns (string memory) { return getTraitName(dungeonId, _DemiGodTag, _demiGods); } function pluckDungeonTrait(uint256 dungeonId, string memory keyPrefix, uint256 traitCount) internal pure returns (uint256) { uint256 rand = random(string(abi.encodePacked(keyPrefix, Strings.toString(dungeonId)))); uint256 index = rand % traitCount; return index; } constructor( uint16 dungeonCount, uint[8] memory startHitPoints, uint256[] memory relicAwards, address raidTokenContract, address lootClassificationAddress, address relicAddress) { _loot = Loot(raidTokenContract); _lootClassification = LootClassification(lootClassificationAddress); _relic = Relic(relicAddress); _relicAwardsByDungeonRank = relicAwards; _nextDungeonCompleteRank = 0; uint256 maxHitPoints; for (uint256 i = 0; i < 8; ++i) { maxHitPoints += startHitPoints[i]; } for (uint16 i = 0; i < dungeonCount; i++) { _dungeons.push(packDungeon(/*rank*/ dungeonCount, startHitPoints, maxHitPoints)); } } event Raid ( uint256 indexed dungeonId, uint256 raidTokenId, uint256[8] damage ); function raidDungeon(uint dungeonId, uint256 raidTokenId) public { require(_raids[raidTokenId] == 0, "loot already used in a raid"); require(msg.sender == _loot.ownerOf(raidTokenId), "raider does not own loot"); uint256 dungeonCount = _dungeons.length; require(dungeonId < dungeonCount, "invalid dungeon"); (uint256 rank, uint256[8] memory dungeonHitPoints, uint256 dungeonMaxHitPoints) = unpackDungeon(_dungeons[dungeonId]); require(rank == dungeonCount, "dungeon already complete"); uint256[9] memory raidHitPoints = _getRaidHitPoints(dungeonId, dungeonHitPoints, raidTokenId); require(raidHitPoints[8] > 0, "raid would have no affect"); bool complete = true; uint256 dungeonTotalHp; for (uint i = 0; i < 8; i++) { dungeonTotalHp += dungeonHitPoints[i]; // it's safe to blind delete the raidHitPoints from the dungeonHitPoints // because the _getRaidHitPoints already limits them to dungeonHitPoints dungeonHitPoints[i] -= raidHitPoints[i]; if (dungeonHitPoints[i] > 0) { complete = false; } } uint256 rewardFirstId = dungeonMaxHitPoints - dungeonTotalHp; uint256 rewardCount = raidHitPoints[8]; _raids[raidTokenId] = packRaid(dungeonId, rewardFirstId, rewardCount); if (complete) { rank = _nextDungeonCompleteRank; _nextDungeonCompleteRank++; } _dungeons[dungeonId] = packDungeon(rank, dungeonHitPoints, dungeonMaxHitPoints); emit Raid(dungeonId, raidTokenId, [ raidHitPoints[0], raidHitPoints[1], raidHitPoints[2], raidHitPoints[3], raidHitPoints[4], raidHitPoints[5], raidHitPoints[6], raidHitPoints[7]]); } struct DungeonInfo { uint256 orderIndex; string enemies; string traps; string bossMonster; string artefact; string passageways; string rooms; string theSoulless; string demiGod; uint256[8] hitPoints; bool isOpen; uint256 rank; int256 rewards; } function getDungeons() external view returns(DungeonInfo[] memory) { DungeonInfo[] memory dungeonInfo = new DungeonInfo[](_dungeons.length); for (uint256 i = 0; i < _dungeons.length; ++i) { dungeonInfo[i].orderIndex = getDungeonOrderIndex(i); dungeonInfo[i].enemies = getEnemies(i); dungeonInfo[i].traps = getTraps(i); dungeonInfo[i].bossMonster = getBossMonster(i); dungeonInfo[i].artefact = getArtefact(i); dungeonInfo[i].passageways = getPassageways(i); dungeonInfo[i].rooms = getRooms(i); dungeonInfo[i].theSoulless = getTheSoulless(i); dungeonInfo[i].demiGod = getDemiGod(i); dungeonInfo[i].hitPoints = getDungeonRemainingHitPoints(i); dungeonInfo[i].isOpen = getDungeonOpen(i); dungeonInfo[i].rank = getDungeonRank(i); dungeonInfo[i].rewards = getDungeonRewardToken(i); } return dungeonInfo; } function getDungeonOrderIndex(uint dungeonId) pure public returns (uint) { return dungeonId % 16; } function getItemHitPoints( uint256 dungeonId, uint256[5] memory lootComponents, string memory traitName, uint256 traitCount, LootClassification.Type lootType) internal view returns(uint) { uint256 dungeonTraitIndex = getTraitIndex(dungeonId, traitName, traitCount); uint256 lootTypeIndex = lootComponents[0]; // Hit points awarded for following // perfect match: 1 // class match with high enough rank: 1 // order match: 2 // order match "+1": 1 bool orderMatch = lootComponents[1] == (getDungeonOrderIndex(dungeonId) + 1); uint256 orderScore; if (orderMatch) { orderScore = 2; if (lootComponents[4] > 0) { orderScore += 1; } } if (dungeonTraitIndex == lootTypeIndex) { // perfect match (and presumed class match) return orderScore + 2; } // there is an order match but not direct hit // if the item is of the correct class and more powerful than exact macth get the order orderScore LootClassification.Class dungeonClass = _lootClassification.getClass(lootType, dungeonTraitIndex); LootClassification.Class lootClass = _lootClassification.getClass(lootType, lootTypeIndex); if (dungeonClass == lootClass && dungeonClass != LootClassification.Class.Any) { uint256 dungeonRank = _lootClassification.getRank(lootType, dungeonTraitIndex); uint256 lootRank = _lootClassification.getRank(lootType, lootTypeIndex); if (lootRank <= dungeonRank) { // class hit of high enough rank return orderScore + 1; } } return orderScore; } function applyRaidItem( uint raidIndex, uint256 raidScore, uint256 maxScore, uint256[9] memory results) pure private { uint256 score = (raidScore > maxScore) ? maxScore : raidScore; results[raidIndex] = score; results[8] += score; } function getRaidHitPoints( uint256 dungeonId, uint256 lootToken) view public returns(uint256[9] memory) { (,uint256[8] memory currentHitPoints,) = unpackDungeon(_dungeons[dungeonId]); return _getRaidHitPoints(dungeonId, currentHitPoints, lootToken); } // returns an array of 8 hitpoints these raids would achieved plus a total in the 9th array slot function _getRaidHitPoints( uint256 dungeonId, uint256[8] memory currentHitPoints, uint256 lootToken) view private returns(uint256[9] memory) { uint256[8] memory itemScores; uint256[9] memory results; if (_raids[lootToken] != 0) { return results; } LootClassification lootClassification = _lootClassification; if (currentHitPoints[0] > 0) { uint256[5] memory weapon = lootClassification.weaponComponents(lootToken); itemScores[0] = getItemHitPoints(dungeonId, weapon, _EnemiesTag, ENEMY_COUNT, LootClassification.Type.Weapon); } if (currentHitPoints[1] > 0) { uint256[5] memory chest = lootClassification.chestComponents(lootToken); itemScores[1] = getItemHitPoints(dungeonId, chest, _TrapsTag, TRAP_COUNT, LootClassification.Type.Chest); } if (currentHitPoints[2] > 0) { uint256[5] memory head = lootClassification.headComponents(lootToken); itemScores[2] = getItemHitPoints(dungeonId, head, _MonsterTag, MONSTER_COUNT, LootClassification.Type.Head); } if (currentHitPoints[3] > 0) { uint256[5] memory waist = lootClassification.waistComponents(lootToken); itemScores[3] = getItemHitPoints(dungeonId, waist, _ArtefactTag, ARTEFACT_COUNT, LootClassification.Type.Waist); } if (currentHitPoints[4] > 0) { uint256[5] memory foot = lootClassification.footComponents(lootToken); itemScores[4] = getItemHitPoints(dungeonId, foot, _PassagewaysTag, PASSAGEWAYS_COUNT, LootClassification.Type.Foot); } if (currentHitPoints[5] > 0) { uint256[5] memory hand = lootClassification.handComponents(lootToken); itemScores[5] = getItemHitPoints(dungeonId, hand, _RoomsTag, ROOM_COUNT, LootClassification.Type.Hand); } if (currentHitPoints[6] > 0) { uint256[5] memory neck = lootClassification.neckComponents(lootToken); itemScores[6] = getItemHitPoints(dungeonId, neck, _TheSoullessTag, SOULLESS_COUNT, LootClassification.Type.Neck); } if (currentHitPoints[7] > 0) { uint256[5] memory ring = lootClassification.ringComponents(lootToken); itemScores[7] = getItemHitPoints(dungeonId, ring, _DemiGodTag, DEMIGOD_COUNT, LootClassification.Type.Ring); } for (uint i = 0; i < 8; i++) { applyRaidItem(i, itemScores[i], currentHitPoints[i], results); } return results; } function getDungeonCount() view public returns(uint256) { if (_dungeons.length == 0) { return 99; } return _dungeons.length; } function getDungeonRemainingHitPoints(uint256 dungeonId) view public returns(uint256[8] memory hitPoints) { (,hitPoints,) = unpackDungeon(_dungeons[dungeonId]); } function getDungeonRank(uint256 dungeonId) view public returns(uint256 rank) { (rank,,) = unpackDungeon(_dungeons[dungeonId]); } function getDungeonOpen(uint256 dungeonId) view public returns(bool) { if (dungeonId >= _dungeons.length) { return false; } return getDungeonRank(dungeonId) == _dungeons.length; } function getDungeonRewardToken(uint256 dungeonId) view public returns (int256) { if (dungeonId >= _dungeons.length) { return -1; } uint256 rank = getDungeonRank(dungeonId); if (rank >= _dungeons.length) { return -1; } return int256(_relicAwardsByDungeonRank[rank]); } function _getRewardsForToken(Loot loot, uint256 dungeonCount, uint256 tokenId) private view returns(uint256 dungeonId, uint256 rewardFirstId, uint256 rewardCount) { require(msg.sender == loot.ownerOf(tokenId), "sender isn't owner of loot"); uint256 packedRaid = _raids[tokenId]; require(packedRaid != 0, "loot bag not used in raid"); (dungeonId, rewardFirstId, rewardCount) = unpackRaid(packedRaid); require(dungeonId < dungeonCount, "invalid dungeon id"); (uint256 rank,,) = unpackDungeon(_dungeons[dungeonId]); require(rank < dungeonCount, "dungeon still open"); rewardFirstId += _relicAwardsByDungeonRank[rank]; } function getRewardsForToken(uint256 tokenId) public view returns(uint256 dungeonId, uint256 rewardFirstId, uint256 rewardCount) { return _getRewardsForToken(_loot, _dungeons.length, tokenId); } function getRewardsForTokens(uint256[] memory tokenIds) public view returns( uint256[] memory dungeonId, uint256[] memory rewardFirstId, uint256[] memory rewardCount) { dungeonId = new uint256[](tokenIds.length); rewardFirstId = new uint256[](tokenIds.length); rewardCount = new uint256[](tokenIds.length); Loot loot = _loot; uint256 dungeonCount = _dungeons.length; for (uint256 i = 0; i < tokenIds.length; ++i) { (dungeonId[i], rewardFirstId[i], rewardCount[i]) = _getRewardsForToken(loot, dungeonCount, tokenIds[i]); } } function claimRewards(uint256[] memory tokenIds) public { uint256 dungeonCount = _dungeons.length; Loot loot = _loot; Relic relic = _relic; for (uint256 i = 0; i < tokenIds.length; ++i) { (uint256 dungeonId, uint256 rewardFirstId, uint256 rewardCount) = _getRewardsForToken(loot, dungeonCount, tokenIds[i]); bytes12 data = bytes12(uint96(dungeonId & 0xffffffffffffffffffffffff)); for (uint256 j = 0; j < rewardCount; ++j) { relic.mint(msg.sender, rewardFirstId + j, data); } } } // // *** Copied from Loot *** // function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } // // *** IRelicMinter Interface *** // string public placeholderImageBaseURL; // this is used when images are not yet pinned string public imageBaseURL; function setImageBaseURL(string memory newImageBaseURL) public onlyOwner { imageBaseURL = newImageBaseURL; } function getTokenOrderIndex(uint256 /*tokenId*/, bytes12 data) external override pure returns(uint) { uint96 dungeonId = uint96(data); return getDungeonOrderIndex(dungeonId); } function getTokenProvenance(uint256 /*tokenId*/, bytes12 /*data*/) external override pure returns(string memory) { return "The Crypt: Chapter One"; } function getAdditionalAttributes(uint256 /*tokenId*/, bytes12 /*data*/) external override pure returns(string memory) { return ""; } function getImageBaseURL() external override view returns(string memory) { if (!(bytes(imageBaseURL).length > 0)) { return placeholderImageBaseURL; } return imageBaseURL; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* LootCLassification.sol Lootverse Utility contract to classifyitems found in Loot (For Adventurers) Bags. See OG Loot Contract for lists of all possible items. https://etherscan.io/address/0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7 All functions are made public incase they are useful but the expected use is through the main 3 classification functions: - getRank() - getClass() - getMaterial() Each of these take an item 'Type' (weapon, chest, head etc.) and an index into the list of all possible items of that type as found in the OG Loot contract. The LootComponents(0x3eb43b1545a360d1D065CB7539339363dFD445F3) contract can be used to get item indexes from Loot bag tokenIDs. The code from LootComponents is copied into this contract and rewritten for gas efficiency So a typical use might be: // get weapon classification for loot bag# 1234 { LootClassification classification = LootClassification(_TBD_); uint256[5] memory weaponComponents = classification.weaponComponents(1234); uint256 index = weaponComponents[0]; LootClassification.Type itemType = LootClassification.Type.Weapon; LootClassification.Class class = classification.getClass(itemType, index); LootClassification.Material material = classification.getMaterial(itemType, index); uint256 rank = classification.getRank(itemType, index); } */ contract LootClassification { enum Type { Weapon, Chest, Head, Waist, Foot, Hand, Neck, Ring } enum Material { Heavy, Medium, Dark, Light, Cloth, Hide, Metal, Jewellery } enum Class { Warrior, Hunter, Mage, Any } uint256 constant public WeaponLastHeavyIndex = 4; uint256 constant public WeaponLastMediumIndex = 9; uint256 constant public WeaponLastDarkIndex = 13; function getWeaponMaterial(uint256 index) pure public returns(Material) { if (index <= WeaponLastHeavyIndex) return Material.Heavy; if (index <= WeaponLastMediumIndex) return Material.Medium; if (index <= WeaponLastDarkIndex) return Material.Dark; return Material.Light; } function getWeaponRank(uint256 index) pure public returns (uint256) { if (index <= WeaponLastHeavyIndex) return index + 1; if (index <= WeaponLastMediumIndex) return index - 4; if (index <= WeaponLastDarkIndex) return index - 9; return index -13; } uint256 constant public ChestLastClothIndex = 4; uint256 constant public ChestLastLeatherIndex = 9; function getChestMaterial(uint256 index) pure public returns(Material) { if (index <= ChestLastClothIndex) return Material.Cloth; if (index <= ChestLastLeatherIndex) return Material.Hide; return Material.Metal; } function getChestRank(uint256 index) pure public returns (uint256) { if (index <= ChestLastClothIndex) return index + 1; if (index <= ChestLastLeatherIndex) return index - 4; return index - 9; } // Head, waist, foot and hand items all follow the same classification pattern, // so they are generalised as armour. uint256 constant public ArmourLastMetalIndex = 4; uint256 constant public ArmourLasLeatherIndex = 9; function getArmourMaterial(uint256 index) pure public returns(Material) { if (index <= ArmourLastMetalIndex) return Material.Metal; if (index <= ArmourLasLeatherIndex) return Material.Hide; return Material.Cloth; } function getArmourRank(uint256 index) pure public returns (uint256) { if (index <= ArmourLastMetalIndex) return index + 1; if (index <= ArmourLasLeatherIndex) return index - 4; return index - 9; } function getRingRank(uint256 index) pure public returns (uint256) { return index + 1; } function getNeckRank(uint256 index) pure public returns (uint256) { return 3 - index; } function getMaterial(Type lootType, uint256 index) pure public returns (Material) { if (lootType == Type.Weapon) return getWeaponMaterial(index); if (lootType == Type.Chest) return getChestMaterial(index); if (lootType == Type.Head || lootType == Type.Waist || lootType == Type.Foot || lootType == Type.Hand) { return getArmourMaterial(index); } return Material.Jewellery; } function getClass(Type lootType, uint256 index) pure public returns (Class) { Material material = getMaterial(lootType, index); return getClassFromMaterial(material); } function getClassFromMaterial(Material material) pure public returns (Class) { if (material == Material.Heavy || material == Material.Metal) return Class.Warrior; if (material == Material.Medium || material == Material.Hide) return Class.Hunter; if (material == Material.Dark || material == Material.Light || material == Material.Cloth) return Class.Mage; return Class.Any; } function getRank(Type lootType, uint256 index) pure public returns (uint256) { if (lootType == Type.Weapon) return getWeaponRank(index); if (lootType == Type.Chest) return getChestRank(index); if (lootType == Type.Head || lootType == Type.Waist || lootType == Type.Foot || lootType == Type.Hand) { return getArmourRank(index); } if (lootType == Type.Ring) return getRingRank(index); return getNeckRank(index); } /////////////////////////////////////////////////////////////////////////// /* Gas efficient implementation of LootComponents https://etherscan.io/address/0x3eb43b1545a360d1D065CB7539339363dFD445F3#code The actual names are not needed when retreiving the component indexes only Header comment from orignal follows: // SPDX-License-Identifier: Unlicense This is a utility contract to make it easier for other contracts to work with Loot properties. Call weaponComponents(), chestComponents(), etc. to get an array of attributes that correspond to the item. The return format is: uint256[5] => [0] = Item ID [1] = Suffix ID (0 for none) [2] = Name Prefix ID (0 for none) [3] = Name Suffix ID (0 for none) [4] = Augmentation (0 = false, 1 = true) See the item and attribute tables below for corresponding IDs. */ uint256 constant WEAPON_COUNT = 18; uint256 constant CHEST_COUNT = 15; uint256 constant HEAD_COUNT = 15; uint256 constant WAIST_COUNT = 15; uint256 constant FOOT_COUNT = 15; uint256 constant HAND_COUNT = 15; uint256 constant NECK_COUNT = 3; uint256 constant RING_COUNT = 5; uint256 constant SUFFIX_COUNT = 16; uint256 constant NAME_PREFIX_COUNT = 69; uint256 constant NAME_SUFFIX_COUNT = 18; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function weaponComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "WEAPON", WEAPON_COUNT); } function chestComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "CHEST", CHEST_COUNT); } function headComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "HEAD", HEAD_COUNT); } function waistComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "WAIST", WAIST_COUNT); } function footComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "FOOT", FOOT_COUNT); } function handComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "HAND", HAND_COUNT); } function neckComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "NECK", NECK_COUNT); } function ringComponents(uint256 tokenId) public pure returns (uint256[5] memory) { return tokenComponents(tokenId, "RING", RING_COUNT); } function tokenComponents(uint256 tokenId, string memory keyPrefix, uint256 itemCount) internal pure returns (uint256[5] memory) { uint256[5] memory components; uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); components[0] = rand % itemCount; components[1] = 0; components[2] = 0; uint256 greatness = rand % 21; if (greatness > 14) { components[1] = (rand % SUFFIX_COUNT) + 1; } if (greatness >= 19) { components[2] = (rand % NAME_PREFIX_COUNT) + 1; components[3] = (rand % NAME_SUFFIX_COUNT) + 1; if (greatness == 19) { // ... } else { components[4] = 1; } } return components; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } } // 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)); } }
there is an order match but not direct hit if the item is of the correct class and more powerful than exact macth get the order orderScore
LootClassification.Class dungeonClass = _lootClassification.getClass(lootType, dungeonTraitIndex);
12,892,010
[ 1, 18664, 353, 392, 1353, 845, 1496, 486, 2657, 6800, 309, 326, 761, 353, 434, 326, 3434, 667, 471, 1898, 7212, 2706, 2353, 5565, 312, 621, 76, 336, 326, 1353, 1353, 7295, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 511, 1632, 19168, 18, 797, 302, 25561, 265, 797, 273, 389, 383, 352, 19168, 18, 588, 797, 12, 383, 352, 559, 16, 302, 25561, 265, 15525, 1016, 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 ]
pragma solidity 0.4.25; // File: contracts/sogur/interfaces/ISGRTokenManager.sol /** * @title SGR Token Manager Interface. */ interface ISGRTokenManager { /** * @dev Exchange ETH for SGR. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGR that the sender is entitled to. */ function exchangeEthForSgr(address _sender, uint256 _ethAmount) external returns (uint256); /** * @dev Handle after the ETH for SGR exchange operation. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @param _sgrAmount The amount of SGR given. */ function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external; /** * @dev Exchange SGR for ETH. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external returns (uint256); /** * @dev Handle after the SGR for ETH exchange operation. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @param _ethAmount The amount of ETH given. * @return The is success result. */ function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool); /** * @dev Handle direct SGR transfer. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external; /** * @dev Handle after direct SGR transfer operation. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferResult The transfer result. * @return is success result. */ function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool); /** * @dev Handle custodian SGR transfer. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external; /** * @dev Handle after custodian SGR transfer operation. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferFromResult The transferFrom result. * @return is success result. */ function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool); /** * @dev Handle the operation of ETH deposit into the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external returns (address, uint256); /** * @dev Handle the operation of ETH withdrawal from the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256); /** * @dev Handle after ETH withdrawal from the SGRToken contract operation. * @param _sender The address of the account which has issued the operation. * @param _wallet The address of the withdrawal wallet. * @param _amount The ETH withdraw amount. * @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. * @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. */ function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external; /** * @dev Upon SGR mint for SGN holders. * @param _value The amount of SGR to mint. */ function uponMintSgrForSgnHolders(uint256 _value) external; /** * @dev Handle after SGR mint for SGN holders. * @param _value The minted amount of SGR. */ function afterMintSgrForSgnHolders(uint256 _value) external; /** * @dev Upon SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function uponTransferSgrToSgnHolder(address _to, uint256 _value) external; /** * @dev Handle after SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The transferred amount of SGR. */ function afterTransferSgrToSgnHolder(address _to, uint256 _value) external; /** * @dev Upon ETH transfer to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external; /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function getDepositParams() external view returns (address, uint256); /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function getWithdrawParams() external view returns (address, uint256); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _ISogurExchanger_ = "ISogurExchanger" ; bytes32 internal constant _SgnToSgrExchangeInitiator_ = "SgnToSgrExchangeInitiator" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGRAuthorizationManager_ = "ISGRAuthorizationManager"; bytes32 internal constant _ISGRToken_ = "ISGRToken" ; bytes32 internal constant _ISGRTokenManager_ = "ISGRTokenManager" ; bytes32 internal constant _ISGRTokenInfo_ = "ISGRTokenInfo" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _BuyWalletsTradingDataSource_ = "BuyWalletsTradingDataSource" ; bytes32 internal constant _SellWalletsTradingDataSource_ = "SellWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _BuyWalletsTradingLimiter_SGRTokenManager_ = "BuyWalletsTLSGRTokenManager" ; bytes32 internal constant _SellWalletsTradingLimiter_SGRTokenManager_ = "SellWalletsTLSGRTokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; bytes32 internal constant _SGAToSGRInitializer_ = "SGAToSGRInitializer" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/sogur/interfaces/IPaymentHandler.sol /** * @title Payment Handler Interface. */ interface IPaymentHandler { /** * @dev Get the amount of available ETH. * @return The amount of available ETH. */ function getEthBalance() external view returns (uint256); /** * @dev Transfer ETH to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. */ function transferEthToSgrHolder(address _to, uint256 _value) external; } // File: contracts/sogur/interfaces/IMintListener.sol /** * @title Mint Listener Interface. */ interface IMintListener { /** * @dev Mint SGR for SGN holders. * @param _value The amount of SGR to mint. */ function mintSgrForSgnHolders(uint256 _value) external; } // File: contracts/saga-genesis/interfaces/ISogurExchanger.sol /** * @title Sogur Exchanger Interface. */ interface ISogurExchanger { /** * @dev Transfer SGR to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function transferSgrToSgnHolder(address _to, uint256 _value) external; } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @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 <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _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 Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: contracts/sogur/interfaces/ISGRTokenInfo.sol /** * @title SGR Token Info Interface. */ interface ISGRTokenInfo { /** * @return the name of the sgr token. */ function getName() external pure returns (string); /** * @return the symbol of the sgr token. */ function getSymbol() external pure returns (string); /** * @return the number of decimals of the sgr token. */ function getDecimals() external pure returns (uint8); } // File: contracts/sogur/SGRToken.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title Sogur Token. * @dev ERC20 compatible. * @dev Exchange ETH for SGR. * @dev Exchange SGR for ETH. */ contract SGRToken is ERC20, ContractAddressLocatorHolder, IMintListener, ISogurExchanger, IPaymentHandler { string public constant VERSION = "2.0.0"; bool public initialized; event SgrTokenInitialized(address indexed _initializer, address _sgaToSGRTokenExchangeAddress, uint256 _sgaToSGRTokenExchangeSGRSupply); /** * @dev Public Address 0x6e9Cd21f2B9033ea0953943c81A041fe203D5E55. * @notice SGR will be minted at this public address for SGN holders. * @notice SGR will be transferred from this public address upon conversion by an SGN holder. * @notice It is generated in a manner which ensures that the corresponding private key is unknown. */ address public constant SGR_MINTED_FOR_SGN_HOLDERS = address(keccak256("SGR_MINTED_FOR_SGN_HOLDERS")); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the ISGRTokenManager interface. */ function getSGRTokenManager() public view returns (ISGRTokenManager) { return ISGRTokenManager(getContractAddress(_ISGRTokenManager_)); } /** * @dev Return the contract which implements ISGRTokenInfo interface. */ function getSGRTokenInfo() public view returns (ISGRTokenInfo) { return ISGRTokenInfo(getContractAddress(_ISGRTokenInfo_)); } /** * @dev Return the sgr token name. */ function name() public view returns (string) { return getSGRTokenInfo().getName(); } /** * @dev Return the sgr token symbol. */ function symbol() public view returns (string){ return getSGRTokenInfo().getSymbol(); } /** * @dev Return the sgr token number of decimals. */ function decimals() public view returns (uint8){ return getSGRTokenInfo().getDecimals(); } /** * @dev Reverts if called when the contract is already initialized. */ modifier onlyIfNotInitialized() { require(!initialized, "contract already initialized"); _; } /** * @dev Exchange ETH for SGR. * @notice Can be executed from externally-owned accounts but not from other contracts. * @notice This is due to the insufficient gas-stipend provided to the fallback function. */ function() external payable { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); uint256 amount = sgrTokenManager.exchangeEthForSgr(msg.sender, msg.value); _mint(msg.sender, amount); sgrTokenManager.afterExchangeEthForSgr(msg.sender, msg.value, amount); } /** * @dev Exchange ETH for SGR. * @notice Can be executed from externally-owned accounts as well as from other contracts. */ function exchange() external payable { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); uint256 amount = sgrTokenManager.exchangeEthForSgr(msg.sender, msg.value); _mint(msg.sender, amount); sgrTokenManager.afterExchangeEthForSgr(msg.sender, msg.value, amount); } /** * @dev Initialize the contract. * @param _sgaToSGRTokenExchangeAddress the contract address. * @param _sgaToSGRTokenExchangeSGRSupply SGR supply for the SGAToSGRTokenExchange contract. */ function init(address _sgaToSGRTokenExchangeAddress, uint256 _sgaToSGRTokenExchangeSGRSupply) external onlyIfNotInitialized only(_SGAToSGRInitializer_) { require(_sgaToSGRTokenExchangeAddress != address(0), "SGA to SGR token exchange address is illegal"); initialized = true; _mint(_sgaToSGRTokenExchangeAddress, _sgaToSGRTokenExchangeSGRSupply); emit SgrTokenInitialized(msg.sender, _sgaToSGRTokenExchangeAddress, _sgaToSGRTokenExchangeSGRSupply); } /** * @dev Transfer SGR to another account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. * @return Status (true if completed successfully, false otherwise). * @notice If the destination account is this contract, then exchange SGR for ETH. */ function transfer(address _to, uint256 _value) public returns (bool) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); if (_to == address(this)) { uint256 amount = sgrTokenManager.exchangeSgrForEth(msg.sender, _value); _burn(msg.sender, _value); msg.sender.transfer(amount); return sgrTokenManager.afterExchangeSgrForEth(msg.sender, _value, amount); } sgrTokenManager.uponTransfer(msg.sender, _to, _value); bool transferResult = super.transfer(_to, _value); return sgrTokenManager.afterTransfer(msg.sender, _to, _value, transferResult); } /** * @dev Transfer SGR from one account to another. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. * @return Status (true if completed successfully, false otherwise). * @notice If the destination account is this contract, then the operation is illegal. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); require(_to != address(this), "custodian-transfer of SGR into this contract is illegal"); sgrTokenManager.uponTransferFrom(msg.sender, _from, _to, _value); bool transferFromResult = super.transferFrom(_from, _to, _value); return sgrTokenManager.afterTransferFrom(msg.sender, _from, _to, _value, transferFromResult); } /** * @dev Deposit ETH into this contract. */ function deposit() external payable { getSGRTokenManager().uponDeposit(msg.sender, address(this).balance, msg.value); } /** * @dev Withdraw ETH from this contract. */ function withdraw() external { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); uint256 priorWithdrawEthBalance = address(this).balance; (address wallet, uint256 amount) = sgrTokenManager.uponWithdraw(msg.sender, priorWithdrawEthBalance); wallet.transfer(amount); sgrTokenManager.afterWithdraw(msg.sender, wallet, amount, priorWithdrawEthBalance, address(this).balance); } /** * @dev Mint SGR for SGN holders. * @param _value The amount of SGR to mint. */ function mintSgrForSgnHolders(uint256 _value) external only(_IMintManager_) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); sgrTokenManager.uponMintSgrForSgnHolders(_value); _mint(SGR_MINTED_FOR_SGN_HOLDERS, _value); sgrTokenManager.afterMintSgrForSgnHolders(_value); } /** * @dev Transfer SGR to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function transferSgrToSgnHolder(address _to, uint256 _value) external only(_SgnToSgrExchangeInitiator_) { ISGRTokenManager sgrTokenManager = getSGRTokenManager(); sgrTokenManager.uponTransferSgrToSgnHolder(_to, _value); _transfer(SGR_MINTED_FOR_SGN_HOLDERS, _to, _value); sgrTokenManager.afterTransferSgrToSgnHolder(_to, _value); } /** * @dev Transfer ETH to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. */ function transferEthToSgrHolder(address _to, uint256 _value) external only(_IPaymentManager_) { bool status = _to.send(_value); getSGRTokenManager().postTransferEthToSgrHolder(_to, _value, status); } /** * @dev Get the amount of available ETH. * @return The amount of available ETH. */ function getEthBalance() external view returns (uint256) { return address(this).balance; } /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in this contract. * @return The address of the reserve-wallet and the deficient amount of ETH in this contract. */ function getDepositParams() external view returns (address, uint256) { return getSGRTokenManager().getDepositParams(); } /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in this contract. * @return The address of the reserve-wallet and the excessive amount of ETH in this contract. */ function getWithdrawParams() external view returns (address, uint256) { return getSGRTokenManager().getWithdrawParams(); } } // File: contracts/sogur/SGRTokenManager.sol /** * Details of usage of licenced software see here: https://www.sogur.com/software/readme_v1 */ /** * @title SGR Token Manager. */ contract SGRTokenManager is ISGRTokenManager, ContractAddressLocatorHolder { string public constant VERSION = "3.0.0"; using SafeMath for uint256; event ExchangeSgrForEthCompleted(address indexed _user, uint256 _input, uint256 _output); event DepositCompleted(address indexed _sender, uint256 _balance, uint256 _amount); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the ISGRToken interface. */ function getSGRToken() public view returns (SGRToken) { return SGRToken(getContractAddress(_ISGRToken_)); } /** * @dev Exchange ETH for SGR. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return Fixed zero as disabled. */ function exchangeEthForSgr(address _sender, uint256 _ethAmount) external returns (uint256) { require(false, "minting new SGR is disabled"); _sender; _ethAmount; return 0; } /** * @dev Handle after the ETH for SGR exchange operation. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @param _sgrAmount The amount of SGR given. */ function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external { require(false, "minting new SGR is disabled"); _sender; _ethAmount; _sgrAmount; } /** * @dev Exchange SGR for ETH. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external only(_ISGRToken_) returns (uint256) { require(_sender != address(0), "sender is illegal"); SGRToken sgrToken = getSGRToken(); require(_sgrAmount <= sgrToken.balanceOf(_sender), "unauthorized SGR amount to exchange"); uint256 ethBalance = sgrToken.getEthBalance(); uint256 sgrTokenTotalSupply = sgrToken.totalSupply(); uint256 ethAmount = (_sgrAmount.mul(ethBalance)).div(sgrTokenTotalSupply); emit ExchangeSgrForEthCompleted(_sender, _sgrAmount, ethAmount); return ethAmount; } /** * @dev Handle after the SGR for ETH exchange operation. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @param _ethAmount The amount of ETH given. * @return The is success result. */ function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool) { _sender; _sgrAmount; _ethAmount; return true; } /** * @dev Handle direct SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external { _sender; _to; _value; } /** * @dev Handle after direct SGR transfer operation. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferResult The transfer result. * @return is success result. */ function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool) { _sender; _to; _value; return _transferResult; } /** * @dev Handle custodian SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external { _sender; _from; _to; _value; } /** * @dev Handle after custodian SGR transfer operation. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferFromResult The transferFrom result. * @return is success result. */ function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool) { _sender; _from; _to; _value; return _transferFromResult; } /** * @dev Handle the operation of ETH deposit into the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract. * @param _amount The deposited ETH amount. * @return Fixed zero as not in use. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external only(_ISGRToken_) returns (address, uint256) { require(_sender != address(0), "sender is illegal"); uint256 ethBalancePriorToDeposit = _balance.sub(_amount); emit DepositCompleted(_sender, ethBalancePriorToDeposit, _amount); return (address(0), 0); } /** * @dev Handle the operation of ETH withdrawal from the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract prior the withdrawal. * @return Fixed zero as disabled. */ function uponWithdraw(address _sender, uint256 _balance) external returns (address, uint256) { require(false, "withdrawal is disabled"); _sender; _balance; return (address(0), 0); } /** * @dev Handle after ETH withdrawal from the SGRToken contract operation. * @param _sender The address of the account which has issued the operation. * @param _wallet The address of the withdrawal wallet. * @param _amount The ETH withdraw amount. * @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. * @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. */ function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external { require(false, "withdrawal is disabled"); _sender; _wallet; _amount; _priorWithdrawEthBalance; _afterWithdrawEthBalance; } /** * @dev Upon SGR mint for SGN holders. * @param _value The amount of SGR to mint. */ function uponMintSgrForSgnHolders(uint256 _value) external { require(false, "minting SGR for SGN holders is disabled"); _value; } /** * @dev Handle after SGR mint for SGN holders. * @param _value The minted amount of SGR. */ function afterMintSgrForSgnHolders(uint256 _value) external { require(false, "minting SGR for SGN holders is disabled"); _value; } /** * @dev Upon SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function uponTransferSgrToSgnHolder(address _to, uint256 _value) external { require(false, "transferring SGR to SGN holders is disabled"); _to; _value; } /** * @dev Handle after SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The transferred amount of SGR. */ function afterTransferSgrToSgnHolder(address _to, uint256 _value) external { require(false, "transferring SGR to SGN holders is disabled"); _to; _value; } /** * @dev Upon ETH transfer to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external { require(false, "postTransferEthToSgrHolder is disabled"); _to; _value; _status; } /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. * @return Fixed zero as not in use. */ function getDepositParams() external view returns (address, uint256) { return (address(0), 0); } /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. * @return Fixed zero as not in use. */ function getWithdrawParams() external view returns (address, uint256) { return (address(0), 0); } }
* @dev Handle after SGR mint for SGN holders. @param _value The minted amount of SGR./
function afterMintSgrForSgnHolders(uint256 _value) external { require(false, "minting SGR for SGN holders is disabled"); _value; }
1,729,518
[ 1, 3259, 1839, 348, 6997, 312, 474, 364, 348, 8318, 366, 4665, 18, 225, 389, 1132, 1021, 312, 474, 329, 3844, 434, 348, 6997, 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, 1839, 49, 474, 55, 3197, 1290, 55, 1600, 27003, 12, 11890, 5034, 389, 1132, 13, 3903, 288, 203, 3639, 2583, 12, 5743, 16, 315, 81, 474, 310, 348, 6997, 364, 348, 8318, 366, 4665, 353, 5673, 8863, 203, 3639, 389, 1132, 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.18; import './IRegistry.sol'; import './Upgradeable.sol'; import './UpgradeabilityProxy.sol'; import './ownership/Ownable.sol'; /** * @title Registry * @dev This contract works as a registry of versions, it holds the implementations for the registered versions. */ contract Registry is IRegistry, Ownable { // Mapping of versions to implementations of different functions mapping (string => address) internal versions; /** * @dev Registers a new version with its implementation address * @param version representing the version name of the new implementation to be registered * @param implementation representing the address of the new implementation to be registered */ function addVersion(string version, address implementation) public { require(versions[version] == 0x0); versions[version] = implementation; VersionAdded(version, implementation); } /** * @dev Tells the address of the implementation for a given version * @param version to query the implementation of * @return address of the implementation registered for the given version */ function getVersion(string version) public view returns (address) { return versions[version]; } /** * @dev Creates an upgradeable proxy * @param version representing the first version to be set for the proxy * @return address of the new proxy created */ function createProxy(string version) public payable returns (UpgradeabilityProxy) { UpgradeabilityProxy proxy = new UpgradeabilityProxy(version); Upgradeable(proxy).initialize.value(msg.value)(msg.sender); ProxyCreated(proxy); return proxy; } /** * @dev Creates an upgradeable proxy * @param proxy value returned from createProxy * @param newowner proxy contract's new owner */ function transferProxyOwnership(address proxy, address newowner) onlyOwner public payable { Ownable(proxy).transferOwnership(newowner); } }
* @dev Registers a new version with its implementation address @param version representing the version name of the new implementation to be registered @param implementation representing the address of the new implementation to be registered/
function addVersion(string version, address implementation) public { require(versions[version] == 0x0); versions[version] = implementation; VersionAdded(version, implementation); }
5,510,956
[ 1, 10277, 279, 394, 1177, 598, 2097, 4471, 1758, 225, 1177, 5123, 326, 1177, 508, 434, 326, 394, 4471, 358, 506, 4104, 225, 4471, 5123, 326, 1758, 434, 326, 394, 4471, 358, 506, 4104, 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, 527, 1444, 12, 1080, 1177, 16, 1758, 4471, 13, 1071, 288, 203, 565, 2583, 12, 10169, 63, 1589, 65, 422, 374, 92, 20, 1769, 203, 565, 5244, 63, 1589, 65, 273, 4471, 31, 203, 565, 4049, 8602, 12, 1589, 16, 4471, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract AccessControl { /// @dev The addresses of the accounts (or contracts) that can execute actions within each roles address public ceoAddress; address public cooAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev The AccessControl constructor sets the original C roles of the contract to the sender account function AccessControl() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Access modifier for any CLevel functionality modifier onlyCLevel() { require(msg.sender == ceoAddress || msg.sender == cooAddress); _; } /// @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) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @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) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @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 Pause the smart contract. Only can be called by the CEO function pause() public onlyCEO whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Only can be called by the CEO function unpause() public onlyCEO whenPaused { paused = false; } } contract RacingClubPresale is AccessControl { using SafeMath for uint256; // Max number of cars (includes sales and gifts) uint256 public constant MAX_CARS = 999; // Max number of cars to gift (includes unicorns) uint256 public constant MAX_CARS_TO_GIFT = 99; // Max number of unicorn cars to gift uint256 public constant MAX_UNICORNS_TO_GIFT = 9; // End date for the presale. No purchases can be made after this date. // Monday, November 19, 2018 11:59:59 PM uint256 public constant PRESALE_END_TIMESTAMP = 1542671999; // Price limits to decrease the appreciation rate uint256 private constant PRICE_LIMIT_1 = 0.1 ether; // Appreciation steps for each price limit uint256 private constant APPRECIATION_STEP_1 = 0.0005 ether; uint256 private constant APPRECIATION_STEP_2 = 0.0001 ether; // Max count which can be bought with one transaction uint256 private constant MAX_ORDER = 5; // 0 - 9 valid Id's for cars uint256 private constant CAR_MODELS = 10; // The special car (the most rarest one) which can't be picked even with MAX_ORDER uint256 public constant UNICORN_ID = 0; // Maps any number from 0 - 255 to 0 - 9 car Id uint256[] private PROBABILITY_MAP = [4, 18, 32, 46, 81, 116, 151, 186, 221, 256]; // Step by which the price should be changed uint256 public appreciationStep = APPRECIATION_STEP_1; // Current price of the car. The price appreciation is happening with each new sale. uint256 public currentPrice = 0.001 ether; // Overall cars count uint256 public carsCount; // Overall gifted cars count uint256 public carsGifted; // Gifted unicorn cars count uint256 public unicornsGifted; // A mapping from addresses to the carIds mapping (address => uint256[]) private ownerToCars; // A mapping from addresses to the upgrade packages mapping (address => uint256) private ownerToUpgradePackages; // Events event CarsPurchased(address indexed _owner, uint256[] _carIds, bool _upgradePackage, uint256 _pricePayed); event CarGifted(address indexed _receiver, uint256 _carId, bool _upgradePackage); function RacingClubPresale() public { // set previous contract values carsCount = 98; carsGifted = 6; unicornsGifted = 2; currentPrice = 0.05 ether; } // Buy a car. The cars are unique within the order. // If order count is 5 then one car can be preselected. function purchaseCars(uint256 _carsToBuy, uint256 _pickedId, bool _upgradePackage) public payable whenNotPaused { require(now < PRESALE_END_TIMESTAMP); require(_carsToBuy > 0 && _carsToBuy <= MAX_ORDER); require(carsCount + _carsToBuy <= MAX_CARS); uint256 priceToPay = calculatePrice(_carsToBuy, _upgradePackage); require(msg.value >= priceToPay); // return excess ether uint256 excess = msg.value.sub(priceToPay); if (excess > 0) { msg.sender.transfer(excess); } // initialize an array for the new cars uint256[] memory randomCars = new uint256[](_carsToBuy); // shows from which point the randomCars array should be filled uint256 startFrom = 0; // for MAX_ORDERs the first item is user picked if (_carsToBuy == MAX_ORDER) { require(_pickedId < CAR_MODELS); require(_pickedId != UNICORN_ID); randomCars[0] = _pickedId; startFrom = 1; } fillRandomCars(randomCars, startFrom); // add new cars to the owner's list for (uint256 i = 0; i < randomCars.length; i++) { ownerToCars[msg.sender].push(randomCars[i]); } // increment upgrade packages if (_upgradePackage) { ownerToUpgradePackages[msg.sender] += _carsToBuy; } CarsPurchased(msg.sender, randomCars, _upgradePackage, priceToPay); carsCount += _carsToBuy; currentPrice += _carsToBuy * appreciationStep; // update this once per purchase // to save the gas and to simplify the calculations updateAppreciationStep(); } // MAX_CARS_TO_GIFT amout of cars are dedicated for gifts function giftCar(address _receiver, uint256 _carId, bool _upgradePackage) public onlyCLevel { // NOTE // Some promo results will be calculated after the presale, // so there is no need to check for the PRESALE_END_TIMESTAMP. require(_carId < CAR_MODELS); require(_receiver != address(0)); // check limits require(carsCount < MAX_CARS); require(carsGifted < MAX_CARS_TO_GIFT); if (_carId == UNICORN_ID) { require(unicornsGifted < MAX_UNICORNS_TO_GIFT); } ownerToCars[_receiver].push(_carId); if (_upgradePackage) { ownerToUpgradePackages[_receiver] += 1; } CarGifted(_receiver, _carId, _upgradePackage); carsCount += 1; carsGifted += 1; if (_carId == UNICORN_ID) { unicornsGifted += 1; } currentPrice += appreciationStep; updateAppreciationStep(); } function calculatePrice(uint256 _carsToBuy, bool _upgradePackage) private view returns (uint256) { // Arithmetic Sequence // A(n) = A(0) + (n - 1) * D uint256 lastPrice = currentPrice + (_carsToBuy - 1) * appreciationStep; // Sum of the First n Terms of an Arithmetic Sequence // S(n) = n * (a(1) + a(n)) / 2 uint256 priceToPay = _carsToBuy * (currentPrice + lastPrice) / 2; // add an extra amount for the upgrade package if (_upgradePackage) { if (_carsToBuy < 3) { priceToPay = priceToPay * 120 / 100; // 20% extra } else if (_carsToBuy < 5) { priceToPay = priceToPay * 115 / 100; // 15% extra } else { priceToPay = priceToPay * 110 / 100; // 10% extra } } return priceToPay; } // Fill unique random cars into _randomCars starting from _startFrom // as some slots may be already filled function fillRandomCars(uint256[] _randomCars, uint256 _startFrom) private view { // All random cars for the current purchase are generated from this 32 bytes. // All purchases within a same block will get different car combinations // as current price is changed at the end of the purchase. // // We don't need super secure random algorithm as it's just presale // and if someone can time the block and grab the desired car we are just happy for him / her bytes32 rand32 = keccak256(currentPrice, now); uint256 randIndex = 0; uint256 carId; for (uint256 i = _startFrom; i < _randomCars.length; i++) { do { // the max number for one purchase is limited to 5 // 32 tries are more than enough to generate 5 unique numbers require(randIndex < 32); carId = generateCarId(uint8(rand32[randIndex])); randIndex++; } while(alreadyContains(_randomCars, carId, i)); _randomCars[i] = carId; } } // Generate a car ID from the given serial number (0 - 255) function generateCarId(uint256 _serialNumber) private view returns (uint256) { for (uint256 i = 0; i < PROBABILITY_MAP.length; i++) { if (_serialNumber < PROBABILITY_MAP[i]) { return i; } } // we should not reach to this point assert(false); } // Check if the given value is already in the list. // By default all items are 0 so _to is used explicitly to validate 0 values. function alreadyContains(uint256[] _list, uint256 _value, uint256 _to) private pure returns (bool) { for (uint256 i = 0; i < _to; i++) { if (_list[i] == _value) { return true; } } return false; } function updateAppreciationStep() private { // this method is called once per purcahse // so use 'greater than' not to miss the limit if (currentPrice > PRICE_LIMIT_1) { // don't update if there is no change if (appreciationStep != APPRECIATION_STEP_2) { appreciationStep = APPRECIATION_STEP_2; } } } function carCountOf(address _owner) public view returns (uint256 _carCount) { return ownerToCars[_owner].length; } function carOfByIndex(address _owner, uint256 _index) public view returns (uint256 _carId) { return ownerToCars[_owner][_index]; } function carsOf(address _owner) public view returns (uint256[] _carIds) { return ownerToCars[_owner]; } function upgradePackageCountOf(address _owner) public view returns (uint256 _upgradePackageCount) { return ownerToUpgradePackages[_owner]; } function allOf(address _owner) public view returns (uint256[] _carIds, uint256 _upgradePackageCount) { return (ownerToCars[_owner], ownerToUpgradePackages[_owner]); } function getStats() public view returns (uint256 _carsCount, uint256 _carsGifted, uint256 _unicornsGifted, uint256 _currentPrice, uint256 _appreciationStep) { return (carsCount, carsGifted, unicornsGifted, currentPrice, appreciationStep); } function withdrawBalance(address _to, uint256 _amount) public onlyCEO { if (_amount == 0) { _amount = address(this).balance; } if (_to == address(0)) { ceoAddress.transfer(_amount); } else { _to.transfer(_amount); } } // Raffle // max count of raffle participants uint256 public raffleLimit = 50; // list of raffle participants address[] private raffleList; // Events event Raffle2Registered(address indexed _iuser, address _user); event Raffle3Registered(address _user); function isInRaffle(address _address) public view returns (bool) { for (uint256 i = 0; i < raffleList.length; i++) { if (raffleList[i] == _address) { return true; } } return false; } function getRaffleStats() public view returns (address[], uint256) { return (raffleList, raffleLimit); } function drawRaffle(uint256 _carId) public onlyCLevel { bytes32 rand32 = keccak256(now, raffleList.length); uint256 winner = uint(rand32) % raffleList.length; giftCar(raffleList[winner], _carId, true); } function resetRaffle() public onlyCLevel { delete raffleList; } function setRaffleLimit(uint256 _limit) public onlyCLevel { raffleLimit = _limit; } // Raffle v1 function registerForRaffle() public { require(raffleList.length < raffleLimit); require(!isInRaffle(msg.sender)); raffleList.push(msg.sender); } // Raffle v2 function registerForRaffle2() public { Raffle2Registered(msg.sender, msg.sender); } // Raffle v3 function registerForRaffle3() public payable { Raffle3Registered(msg.sender); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
@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) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; }
6,981,766
[ 1, 24842, 279, 394, 1758, 358, 1328, 487, 326, 7910, 51, 18, 5098, 2319, 358, 326, 783, 29538, 51, 225, 389, 2704, 3865, 51, 1021, 1758, 434, 326, 394, 7910, 51, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 3865, 51, 12, 2867, 389, 2704, 3865, 51, 13, 1071, 1338, 1441, 51, 288, 203, 565, 2583, 24899, 2704, 3865, 51, 480, 1758, 12, 20, 10019, 203, 565, 1825, 83, 1887, 273, 389, 2704, 3865, 51, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x00000000007767d79f9F4aA1Ff0d71b8E2E4a231/sources/node_modules/@looksrare/contracts-libs/contracts/SignatureCheckerMemory.sol
* @title SignatureCheckerMemory @notice This library is used to verify signatures for EOAs (with lengths of both 65 and 64 bytes) and contracts (ERC1271). @author LooksRare protocol team (👀,💎)/
library SignatureCheckerMemory { pragma solidity ^0.8.17; import {IERC1271} from "./interfaces/generic/IERC1271.sol"; import {ERC1271_MAGIC_VALUE} from "./constants/StandardConstants.sol"; import {SignatureParameterSInvalid, SignatureParameterVInvalid, SignatureERC1271Invalid, SignatureEOAInvalid, NullSignerAddress, SignatureLengthInvalid} from "./errors/SignatureCheckerErrors.sol"; function verify(bytes32 hash, address signer, bytes memory signature) internal view { if (signer.code.length == 0) { if (_recoverEOASigner(hash, signature) == signer) return; revert SignatureEOAInvalid(); if (IERC1271(signer).isValidSignature(hash, signature) == ERC1271_MAGIC_VALUE) return; revert SignatureERC1271Invalid(); } } function verify(bytes32 hash, address signer, bytes memory signature) internal view { if (signer.code.length == 0) { if (_recoverEOASigner(hash, signature) == signer) return; revert SignatureEOAInvalid(); if (IERC1271(signer).isValidSignature(hash, signature) == ERC1271_MAGIC_VALUE) return; revert SignatureERC1271Invalid(); } } } else { function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { uint256 length = signature.length; if (length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { r := mload(add(signature, 0x20)) let vs := mload(add(signature, 0x40)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } revert SignatureLengthInvalid(length); } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert SignatureParameterSInvalid(); } if (v != 27 && v != 28) { revert SignatureParameterVInvalid(v); } } function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { uint256 length = signature.length; if (length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { r := mload(add(signature, 0x20)) let vs := mload(add(signature, 0x40)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } revert SignatureLengthInvalid(length); } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert SignatureParameterSInvalid(); } if (v != 27 && v != 28) { revert SignatureParameterVInvalid(v); } } function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { uint256 length = signature.length; if (length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { r := mload(add(signature, 0x20)) let vs := mload(add(signature, 0x40)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } revert SignatureLengthInvalid(length); } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert SignatureParameterSInvalid(); } if (v != 27 && v != 28) { revert SignatureParameterVInvalid(v); } } } else if (length == 64) { function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { uint256 length = signature.length; if (length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { r := mload(add(signature, 0x20)) let vs := mload(add(signature, 0x40)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } revert SignatureLengthInvalid(length); } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert SignatureParameterSInvalid(); } if (v != 27 && v != 28) { revert SignatureParameterVInvalid(v); } } } else { function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { uint256 length = signature.length; if (length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { r := mload(add(signature, 0x20)) let vs := mload(add(signature, 0x40)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } revert SignatureLengthInvalid(length); } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert SignatureParameterSInvalid(); } if (v != 27 && v != 28) { revert SignatureParameterVInvalid(v); } } function splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { uint256 length = signature.length; if (length == 65) { assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } assembly { r := mload(add(signature, 0x20)) let vs := mload(add(signature, 0x40)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } revert SignatureLengthInvalid(length); } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert SignatureParameterSInvalid(); } if (v != 27 && v != 28) { revert SignatureParameterVInvalid(v); } } function _recoverEOASigner(bytes32 hash, bytes memory signature) private pure returns (address signer) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); signer = ecrecover(hash, v, r, s); if (signer == address(0)) { revert NullSignerAddress(); } } function _recoverEOASigner(bytes32 hash, bytes memory signature) private pure returns (address signer) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); signer = ecrecover(hash, v, r, s); if (signer == address(0)) { revert NullSignerAddress(); } } }
16,178,158
[ 1, 5374, 8847, 6031, 225, 1220, 5313, 353, 1399, 358, 3929, 14862, 364, 512, 51, 1463, 261, 1918, 10917, 434, 3937, 15892, 471, 5178, 1731, 13, 540, 471, 20092, 261, 654, 39, 2138, 11212, 2934, 225, 10176, 87, 54, 834, 1771, 5927, 261, 177, 258, 244, 227, 16, 177, 258, 245, 241, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 12083, 9249, 8847, 6031, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 4033, 31, 203, 5666, 288, 45, 654, 39, 2138, 11212, 97, 628, 25165, 15898, 19, 13540, 19, 45, 654, 39, 2138, 11212, 18, 18281, 14432, 203, 5666, 288, 654, 39, 2138, 11212, 67, 49, 22247, 67, 4051, 97, 628, 25165, 13358, 19, 8336, 2918, 18, 18281, 14432, 203, 5666, 288, 5374, 1662, 55, 1941, 16, 9249, 1662, 58, 1941, 16, 9249, 654, 39, 2138, 11212, 1941, 16, 9249, 41, 28202, 1941, 16, 4112, 15647, 1887, 16, 9249, 1782, 1941, 97, 628, 25165, 4324, 19, 5374, 8847, 4229, 18, 18281, 14432, 203, 565, 445, 3929, 12, 3890, 1578, 1651, 16, 1758, 10363, 16, 1731, 3778, 3372, 13, 2713, 1476, 288, 203, 3639, 309, 261, 2977, 264, 18, 710, 18, 2469, 422, 374, 13, 288, 203, 5411, 309, 261, 67, 266, 3165, 41, 28202, 15647, 12, 2816, 16, 3372, 13, 422, 10363, 13, 327, 31, 203, 5411, 15226, 9249, 41, 28202, 1941, 5621, 203, 5411, 309, 261, 45, 654, 39, 2138, 11212, 12, 2977, 264, 2934, 26810, 5374, 12, 2816, 16, 3372, 13, 422, 4232, 39, 2138, 11212, 67, 49, 22247, 67, 4051, 13, 327, 31, 203, 5411, 15226, 9249, 654, 39, 2138, 11212, 1941, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 3929, 12, 3890, 1578, 1651, 16, 1758, 10363, 16, 1731, 3778, 3372, 13, 2713, 1476, 288, 203, 3639, 309, 261, 2977, 264, 18, 710, 18, 2469, 422, 374, 13, 288, 203, 5411, 309, 261, 67, 2 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol 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; } } // File: contracts/interfaces/INsure.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface INsure { function burn(uint256 amount) external ; function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function mint(address _to, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } // File: contracts/Treasury.sol /** * @dev a contract for locking Nsure Token to be an underwriter. * * @notice the underwriter program would be calculated and recorded by central ways which is too complicated for contracts(gas used etc.) */ pragma solidity ^0.6.0; contract Treasury is Ownable, ReentrancyGuard{ using SafeMath for uint256; using SafeERC20 for IERC20; address public constant ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address public signer; string constant public name = "Treasury"; string public constant version = "1"; uint256 public depositMax = 1 * 1e6 * 1e18; uint256 public deadlineDuration = 30 minutes; address public operator; /// @notice A record of states for signing / validating signatures mapping (address => uint256) public nonces; struct DivCurrency { address divCurrency; uint256 limit; } DivCurrency[] public divCurrencies; INsure public Nsure; uint256 private _totalSupply; uint256 public claimDuration = 30 minutes; mapping(address => uint256) private _balances; mapping(address => uint256) public claimAt; modifier onlyOperator() { require(msg.sender == operator,"not operator"); _; } /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant CLAIM_TYPEHASH = keccak256("Claim(address account,uint256 currency,uint256 amount,uint256 nonce,uint256 deadline)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant WITHDRAW_TYPEHASH = keccak256("Withdraw(address account,uint256 amount,uint256 nonce,uint256 deadline)"); constructor(address _signer, address _nsure)public { Nsure = INsure(_nsure); signer = _signer; } receive() external payable {} function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } // payout for claiming function payouts(address payable _to, uint256 _amount, address token) external onlyOperator { require(_to != address(0),"_to is zero"); if (token != ETHEREUM) { IERC20(token).safeTransfer(_to, _amount); } else { _to.transfer(_amount); } emit ePayouts(_to, _amount); } // return my token balance function myBalanceOf(address tokenAddress) external view returns(uint256) { return IERC20(tokenAddress).balanceOf(address(this)); } function setClaimDuration(uint256 _duration)external onlyOwner { require(claimDuration != _duration, "the same duration"); claimDuration = _duration; emit SetClaimDuration(_duration); } function setSigner(address _signer) external onlyOwner { require(_signer != address(0),"_signer is zero"); signer = _signer; emit SetSigner(_signer); } function setOperator(address _operator) external onlyOwner { require(_operator != address(0),"_operator is zero"); operator = _operator; emit SetOperator(_operator); } function setDeadlineDuration(uint256 _duration) external onlyOwner { deadlineDuration = _duration; emit SetDeadlineDuration(_duration); } function getDivCurrencyLength() external view returns (uint256) { return divCurrencies.length; } function addDivCurrency(address _currency,uint256 _limit) external onlyOwner { require(_currency != address(0),"_currency is zero"); divCurrencies.push(DivCurrency({divCurrency:_currency, limit:_limit})); } function setDepositMax(uint256 _max) external onlyOwner { depositMax = _max; emit SetDepositMax(_max); } function deposit(uint256 amount) external nonReentrant{ require(amount > 0, "Cannot stake 0"); require(amount <= depositMax,"exceeding the maximum limit"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // Nsure.transferFrom(msg.sender, address(this), amount); Nsure.transferFrom(msg.sender,address(this),amount); emit Deposit(msg.sender, amount); } function withdraw(uint256 _amount,uint256 deadline,uint8 v, bytes32 r, bytes32 s) external nonReentrant { require(_balances[msg.sender] >= _amount,"insufficient"); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(WITHDRAW_TYPEHASH, address(msg.sender), _amount,nonces[msg.sender]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "invalid signature"); require(signatory == signer, "unauthorized"); require(block.timestamp <= deadline, "signature expired"); _balances[msg.sender] = _balances[msg.sender].sub(_amount); Nsure.transfer(msg.sender,_amount); emit Withdraw(msg.sender,_amount,nonces[msg.sender]-1); } // burn 1/2 for claiming function burnOuts(address[] calldata _burnUsers, uint256[] calldata _amounts) external onlyOperator { require(_burnUsers.length == _amounts.length, "not equal"); for(uint256 i = 0; i<_burnUsers.length; i++) { require(_balances[_burnUsers[i]] >= _amounts[i], "insufficient"); _balances[_burnUsers[i]] = _balances[_burnUsers[i]].sub(_amounts[i]); Nsure.burn(_amounts[i]); emit Burn(_burnUsers[i],_amounts[i]); } } function claim(uint256 _amount, uint256 currency, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant { require(block.timestamp > claimAt[msg.sender].add(claimDuration), "wait" ); require(block.timestamp.add(deadlineDuration) > deadline, "expired"); require(_amount <= divCurrencies[currency].limit, "exceeding the maximum limit"); require(block.timestamp <= deadline, "signature expired"); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)),keccak256(bytes(version)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(CLAIM_TYPEHASH,address(msg.sender), currency, _amount,nonces[msg.sender]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "invalid signature"); require(signatory == signer, "unauthorized"); claimAt[msg.sender] = block.timestamp; IERC20(divCurrencies[currency].divCurrency).safeTransfer(msg.sender,_amount); emit Claim(msg.sender,currency,_amount,nonces[msg.sender] -1); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount,uint256 nonce); event Claim(address indexed user,uint256 currency,uint256 amount,uint256 nonce); event Burn(address indexed user,uint256 amount); event SetOperator(address indexed operator); event SetClaimDuration(uint256 duration); event SetSigner(address indexed signer); event SetDeadlineDuration(uint256 deadlineDuration); event SetDepositMax(uint256 depositMax); /////////// events ///////////// event ePayouts(address indexed to, uint256 amount); event eSetOperator(address indexed operator); }
payout for claiming
function payouts(address payable _to, uint256 _amount, address token) external onlyOperator { require(_to != address(0),"_to is zero"); if (token != ETHEREUM) { IERC20(token).safeTransfer(_to, _amount); _to.transfer(_amount); } emit ePayouts(_to, _amount); }
1,644,028
[ 1, 84, 2012, 364, 7516, 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, 565, 445, 293, 2012, 87, 12, 2867, 8843, 429, 389, 869, 16, 2254, 5034, 389, 8949, 16, 1758, 1147, 13, 3903, 1338, 5592, 288, 203, 540, 2583, 24899, 869, 480, 1758, 12, 20, 3631, 6, 67, 869, 353, 3634, 8863, 203, 3639, 309, 261, 2316, 480, 512, 19905, 41, 2799, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 2316, 2934, 4626, 5912, 24899, 869, 16, 389, 8949, 1769, 203, 5411, 389, 869, 18, 13866, 24899, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 425, 52, 2012, 87, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/421613/0x16dc09965582F69Ca6669eDD8A5dE2052209eBE3/sources/src/facets/TokenFacet.sol
* @dev Returns the name of the token./
function name() public view virtual returns (string memory) { return TokenLib.getStorage()._name; }
11,582,165
[ 1, 1356, 326, 508, 434, 326, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 508, 1435, 1071, 1476, 5024, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 3155, 5664, 18, 588, 3245, 1435, 6315, 529, 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 ]
pragma solidity 0.5.8; /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } interface IMiniMeToken { function balanceOf(address _owner) external view returns (uint256 balance); function totalSupply() external view returns(uint); function generateTokens(address _owner, uint _amount) external returns (bool); function destroyTokens(address _owner, uint _amount) external returns (bool); function totalSupplyAt(uint _blockNumber) external view returns(uint); function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint); function transferOwnership(address newOwner) external; } /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } /** * @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. * * > 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 Optional functions from the ERC20 standard. */ contract ERC20Detailed 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. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _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 that 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 Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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); 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"); } } } /** * @title The interface for the Kyber Network smart contract * @author Zefram Lou (Zebang Liu) */ interface KyberNetwork { function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); } /** * @title The smart contract for useful utility functions and constants. * @author Zefram Lou (Zebang Liu) */ contract Utils { using SafeMath for uint256; using SafeERC20 for ERC20Detailed; /** * @notice Checks if `_token` is a valid token. * @param _token the token's address */ modifier isValidToken(address _token) { require(_token != address(0)); if (_token != address(ETH_TOKEN_ADDRESS)) { require(isContract(_token)); } _; } address public DAI_ADDR; address payable public KYBER_ADDR; bytes public constant PERM_HINT = "PERM"; ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20Detailed internal dai; KyberNetwork internal kyber; uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal ETH_DECIMALS = 18; uint constant internal MAX_DECIMALS = 18; constructor( address _daiAddr, address payable _kyberAddr ) public { DAI_ADDR = _daiAddr; KYBER_ADDR = _kyberAddr; dai = ERC20Detailed(_daiAddr); kyber = KyberNetwork(_kyberAddr); } /** * @notice Get the number of decimals of a token * @param _token the token to be queried * @return number of decimals */ function getDecimals(ERC20Detailed _token) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(ETH_DECIMALS); } return uint256(_token.decimals()); } /** * @notice Get the token balance of an account * @param _token the token to be queried * @param _addr the account whose balance will be returned * @return token balance of the account */ function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(_addr.balance); } return uint256(_token.balanceOf(_addr)); } /** * @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals. * Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate * from A to B is 10 * 10**18, regardless of how many decimals each token uses. * @param srcAmount amount of source token * @param destAmount amount of dest token * @param srcDecimals decimals used by source token * @param dstDecimals decimals used by dest token */ function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } /** * @notice Wrapper function for doing token conversion on Kyber Network * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); // Get current rate & ensure token is listed on Kyber (, uint256 rate) = kyber.getExpectedRate(_srcToken, _destToken, _srcAmount); require(rate > 0); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 msgValue; if (_srcToken != ETH_TOKEN_ADDRESS) { msgValue = 0; _srcToken.safeApprove(KYBER_ADDR, 0); _srcToken.safeApprove(KYBER_ADDR, _srcAmount); } else { msgValue = _srcAmount; } _actualDestAmount = kyber.tradeWithHint.value(msgValue)( _srcToken, _srcAmount, _destToken, toPayableAddr(address(this)), MAX_QTY, rate, 0x332D87209f7c8296389C307eAe170c2440830A47, PERM_HINT ); require(_actualDestAmount > 0); if (_srcToken != ETH_TOKEN_ADDRESS) { _srcToken.safeApprove(KYBER_ADDR, 0); } _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Checks if an Ethereum account is a smart contract * @param _addr the account to be checked * @return True if the account is a smart contract, false otherwise */ function isContract(address _addr) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } function toPayableAddr(address _addr) pure internal returns (address payable) { return address(uint160(_addr)); } } interface BetokenProxyInterface { function betokenFundAddress() external view returns (address payable); function updateBetokenFundAddress() external; } /** * @title The storage layout of BetokenFund * @author Zefram Lou (Zebang Liu) */ contract BetokenStorage is Ownable, ReentrancyGuard { using SafeMath for uint256; enum CyclePhase { Intermission, Manage } enum VoteDirection { Empty, For, Against } enum Subchunk { Propose, Vote } struct Investment { address tokenAddress; uint256 cycleNumber; uint256 stake; uint256 tokenAmount; uint256 buyPrice; // token buy price in 18 decimals in DAI uint256 sellPrice; // token sell price in 18 decimals in DAI uint256 buyTime; uint256 buyCostInDAI; bool isSold; } // Fund parameters uint256 public constant COMMISSION_RATE = 20 * (10 ** 16); // The proportion of profits that gets distributed to Kairo holders every cycle. uint256 public constant ASSET_FEE_RATE = 1 * (10 ** 15); // The proportion of fund balance that gets distributed to Kairo holders every cycle. uint256 public constant NEXT_PHASE_REWARD = 1 * (10 ** 18); // Amount of Kairo rewarded to the user who calls nextPhase(). uint256 public constant MAX_BUY_KRO_PROP = 1 * (10 ** 16); // max Kairo you can buy is 1% of total supply uint256 public constant FALLBACK_MAX_DONATION = 100 * (10 ** 18); // If payment cap for registration is below 100 DAI, use 100 DAI instead uint256 public constant MIN_KRO_PRICE = 25 * (10 ** 17); // 1 KRO >= 2.5 DAI uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10 ** 16); // Modifies Compound's collateral ratio, gets 2:1 ratio from current 1.5:1 ratio uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * kairoBalance uint256 public constant INACTIVE_THRESHOLD = 6; // Number of inactive cycles after which a manager's Kairo balance can be burned // Upgrade constants uint256 public constant CHUNK_SIZE = 3 days; uint256 public constant PROPOSE_SUBCHUNK_SIZE = 1 days; uint256 public constant CYCLES_TILL_MATURITY = 3; uint256 public constant QUORUM = 10 * (10 ** 16); // 10% quorum uint256 public constant VOTE_SUCCESS_THRESHOLD = 75 * (10 ** 16); // Votes on upgrade candidates need >75% voting weight to pass // Instance variables // Checks if the token listing initialization has been completed. bool public hasInitializedTokenListings; // Address of the Kairo token contract. address public controlTokenAddr; // Address of the share token contract. address public shareTokenAddr; // Address of the BetokenProxy contract. address payable public proxyAddr; // Address of the CompoundOrderFactory contract. address public compoundFactoryAddr; // Address of the BetokenLogic contract. address public betokenLogic; // Address to which the development team funding will be sent. address payable public devFundingAccount; // Address of the previous version of BetokenFund. address payable public previousVersion; // The number of the current investment cycle. uint256 public cycleNumber; // The amount of funds held by the fund. uint256 public totalFundsInDAI; // The start time for the current investment cycle phase, in seconds since Unix epoch. uint256 public startTimeOfCyclePhase; // The proportion of Betoken Shares total supply to mint and use for funding the development team. Fixed point decimal. uint256 public devFundingRate; // Total amount of commission unclaimed by managers uint256 public totalCommissionLeft; // Stores the lengths of each cycle phase in seconds. uint256[2] public phaseLengths; // The last cycle where a user redeemed all of their remaining commission. mapping(address => uint256) public lastCommissionRedemption; // Marks whether a manager has redeemed their commission for a certain cycle mapping(address => mapping(uint256 => bool)) public hasRedeemedCommissionForCycle; // The stake-time measured risk that a manager has taken in a cycle mapping(address => mapping(uint256 => uint256)) public riskTakenInCycle; // In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation mapping(address => uint256) public baseRiskStakeFallback; // List of investments of a manager in the current cycle. mapping(address => Investment[]) public userInvestments; // List of short/long orders of a manager in the current cycle. mapping(address => address payable[]) public userCompoundOrders; // Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission) mapping(uint256 => uint256) public totalCommissionOfCycle; // The block number at which the Manage phase ended for a given cycle mapping(uint256 => uint256) public managePhaseEndBlock; // The last cycle where a manager made an investment mapping(address => uint256) public lastActiveCycle; // Checks if an address points to a whitelisted Kyber token. mapping(address => bool) public isKyberToken; // Checks if an address points to a whitelisted Compound token. Returns false for cDAI and other stablecoin CompoundTokens. mapping(address => bool) public isCompoundToken; // Check if an address points to a whitelisted Fulcrum position token. mapping(address => bool) public isPositionToken; // The current cycle phase. CyclePhase public cyclePhase; // Upgrade governance related variables bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized bool public upgradeVotingActive; // Denotes if the vote for which contract to upgrade to is active address payable public nextVersion; // Address of the next version of BetokenFund. address[5] public proposers; // Manager who proposed the upgrade candidate in a chunk address payable[5] public candidates; // Candidates for a chunk uint256[5] public forVotes; // For votes for a chunk uint256[5] public againstVotes; // Against votes for a chunk uint256 public proposersVotingWeight; // Total voting weight of previous and current proposers. This is used for excluding the voting weight of proposers. mapping(uint256 => mapping(address => VoteDirection[5])) public managerVotes; // Records each manager's vote mapping(uint256 => uint256) public upgradeSignalStrength; // Denotes the amount of Kairo that's signalling in support of beginning the upgrade process during a cycle mapping(uint256 => mapping(address => bool)) public upgradeSignal; // Maps manager address to whether they support initiating an upgrade // Contract instances IMiniMeToken internal cToken; IMiniMeToken internal sToken; BetokenProxyInterface internal proxy; // Events event ChangedPhase(uint256 indexed _cycleNumber, uint256 indexed _newPhase, uint256 _timestamp, uint256 _totalFundsInDAI); event Deposit(uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _daiAmount, uint256 _timestamp); event Withdraw(uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _daiAmount, uint256 _timestamp); event CreatedInvestment(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _stakeInWeis, uint256 _buyPrice, uint256 _costDAIAmount, uint256 _tokenAmount); event SoldInvestment(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _receivedKairo, uint256 _sellPrice, uint256 _earnedDAIAmount); event CreatedCompoundOrder(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _stakeInWeis, uint256 _costDAIAmount); event SoldCompoundOrder(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _receivedKairo, uint256 _earnedDAIAmount); event RepaidCompoundOrder(uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, uint256 _repaidDAIAmount); event CommissionPaid(uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission); event TotalCommissionPaid(uint256 indexed _cycleNumber, uint256 _totalCommissionInDAI); event Register(address indexed _manager, uint256 _donationInDAI, uint256 _kairoReceived); event SignaledUpgrade(uint256 indexed _cycleNumber, address indexed _sender, bool indexed _inSupport); event DeveloperInitiatedUpgrade(uint256 indexed _cycleNumber, address _candidate); event InitiatedUpgrade(uint256 indexed _cycleNumber); event ProposedCandidate(uint256 indexed _cycleNumber, uint256 indexed _voteID, address indexed _sender, address _candidate); event Voted(uint256 indexed _cycleNumber, uint256 indexed _voteID, address indexed _sender, bool _inSupport, uint256 _weight); event FinalizedNextVersion(uint256 indexed _cycleNumber, address _nextVersion); /* Helper functions shared by both BetokenLogic & BetokenFund */ /** * @notice The manage phase is divided into 9 3-day chunks. Determines which chunk the fund's in right now. * @return The index of the current chunk (starts from 0). Returns 0 if not in Manage phase. */ function currentChunk() public view returns (uint) { if (cyclePhase != CyclePhase.Manage) { return 0; } return (now - startTimeOfCyclePhase) / CHUNK_SIZE; } /** * @notice There are two subchunks in each chunk: propose (1 day) and vote (2 days). * Determines which subchunk the fund is in right now. * @return The Subchunk the fund is in right now */ function currentSubchunk() public view returns (Subchunk _subchunk) { if (cyclePhase != CyclePhase.Manage) { return Subchunk.Vote; } uint256 timeIntoCurrChunk = (now - startTimeOfCyclePhase) % CHUNK_SIZE; return timeIntoCurrChunk < PROPOSE_SUBCHUNK_SIZE ? Subchunk.Propose : Subchunk.Vote; } /** * @notice Calculates an account's voting weight based on their Kairo balance * 3 cycles ago * @param _of the account to be queried * @return The account's voting weight */ function getVotingWeight(address _of) public view returns (uint256 _weight) { if (cycleNumber <= CYCLES_TILL_MATURITY || _of == address(0)) { return 0; } return cToken.balanceOfAt(_of, managePhaseEndBlock[cycleNumber.sub(CYCLES_TILL_MATURITY)]); } /** * @notice Calculates the total voting weight based on the total Kairo supply * 3 cycles ago. The weights of proposers are deducted. * @return The total voting weight right now */ function getTotalVotingWeight() public view returns (uint256 _weight) { if (cycleNumber <= CYCLES_TILL_MATURITY) { return 0; } return cToken.totalSupplyAt(managePhaseEndBlock[cycleNumber.sub(CYCLES_TILL_MATURITY)]).sub(proposersVotingWeight); } /** * @notice Calculates the current price of Kairo. The price is equal to the amount of DAI each Kairo * can control, and it's kept above MIN_KRO_PRICE. * @return Kairo's current price */ function kairoPrice() public view returns (uint256 _kairoPrice) { if (cToken.totalSupply() == 0) { return MIN_KRO_PRICE; } uint256 controlPerKairo = totalFundsInDAI.mul(10 ** 18).div(cToken.totalSupply()); if (controlPerKairo < MIN_KRO_PRICE) { // keep price above minimum price return MIN_KRO_PRICE; } return controlPerKairo; } } // Compound finance comptroller interface Comptroller { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa); } // Compound finance's price oracle interface PriceOracle { function getPrice(address asset) external view returns (uint); } // Compound finance ERC20 market interface interface CERC20 { function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); function underlying() external view returns (address); } contract CompoundOrderStorage is Ownable { // Constants uint256 internal constant NEGLIGIBLE_DEBT = 10 ** 14; // we don't care about debts below 10^-4 DAI (0.1 cent) uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt // Contract instances Comptroller public COMPTROLLER; // The Compound comptroller PriceOracle public ORACLE; // The Compound price oracle CERC20 public CDAI; // The Compound DAI market token address public CETH_ADDR; // Instance variables uint256 public stake; uint256 public collateralAmountInDAI; uint256 public loanAmountInDAI; uint256 public cycleNumber; uint256 public buyTime; // Timestamp for order execution uint256 public outputAmount; // Records the total output DAI after order is sold address public compoundTokenAddr; bool public isSold; bool public orderType; // True for shorting, false for longing // The contract containing the code to be executed address public logicContract; } contract CompoundOrder is CompoundOrderStorage, Utils { constructor( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInDAI, uint256 _loanAmountInDAI, bool _orderType, address _logicContract, address _daiAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cDAIAddr, address _cETHAddr ) public Utils(_daiAddr, _kyberAddr) { // Initialize details of short order require(_compoundTokenAddr != _cDAIAddr); require(_stake > 0 && _collateralAmountInDAI > 0 && _loanAmountInDAI > 0); // Validate inputs stake = _stake; collateralAmountInDAI = _collateralAmountInDAI; loanAmountInDAI = _loanAmountInDAI; cycleNumber = _cycleNumber; compoundTokenAddr = _compoundTokenAddr; orderType = _orderType; logicContract = _logicContract; COMPTROLLER = Comptroller(_comptrollerAddr); ORACLE = PriceOracle(_priceOracleAddr); CDAI = CERC20(_cDAIAddr); CETH_ADDR = _cETHAddr; } /** * @notice Executes the Compound order * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function executeOrder(uint256 _minPrice, uint256 _maxPrice) public { (bool success,) = logicContract.delegatecall(abi.encodeWithSelector(this.executeOrder.selector, _minPrice, _maxPrice)); if (!success) { revert(); } } /** * @notice Sells the Compound order and returns assets to BetokenFund * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.sellOrder.selector, _minPrice, _maxPrice)); if (!success) { revert(); } return abi.decode(result, (uint256, uint256)); } /** * @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold * @param _repayAmountInDAI the amount to repay, in DAI */ function repayLoan(uint256 _repayAmountInDAI) public { (bool success,) = logicContract.delegatecall(abi.encodeWithSelector(this.repayLoan.selector, _repayAmountInDAI)); if (!success) { revert(); } } /** * @notice Calculates the current liquidity (supply - collateral) on the Compound platform * @return the liquidity */ function getCurrentLiquidityInDAI() public returns (bool _isNegative, uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentLiquidityInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (bool, uint256)); } /** * @notice Calculates the current collateral ratio on Compound, using 18 decimals * @return the collateral ratio */ function getCurrentCollateralRatioInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentCollateralRatioInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } /** * @notice Calculates the current profit in DAI * @return the profit amount */ function getCurrentProfitInDAI() public returns (bool _isNegative, uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentProfitInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (bool, uint256)); } function getMarketCollateralFactor() public returns (uint256) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getMarketCollateralFactor.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function getCurrentCollateralInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentCollateralInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function getCurrentBorrowInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentBorrowInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function getCurrentCashInDAI() public returns (uint256 _amount) { (bool success, bytes memory result) = logicContract.delegatecall(abi.encodeWithSelector(this.getCurrentCashInDAI.selector)); if (!success) { revert(); } return abi.decode(result, (uint256)); } function() external payable {} } contract CompoundOrderFactory { address public SHORT_CERC20_LOGIC_CONTRACT; address public SHORT_CEther_LOGIC_CONTRACT; address public LONG_CERC20_LOGIC_CONTRACT; address public LONG_CEther_LOGIC_CONTRACT; address public DAI_ADDR; address payable public KYBER_ADDR; address public COMPTROLLER_ADDR; address public ORACLE_ADDR; address public CDAI_ADDR; address public CETH_ADDR; constructor( address _shortCERC20LogicContract, address _shortCEtherLogicContract, address _longCERC20LogicContract, address _longCEtherLogicContract, address _daiAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cDAIAddr, address _cETHAddr ) public { SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract; SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract; LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract; LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract; DAI_ADDR = _daiAddr; KYBER_ADDR = _kyberAddr; COMPTROLLER_ADDR = _comptrollerAddr; ORACLE_ADDR = _priceOracleAddr; CDAI_ADDR = _cDAIAddr; CETH_ADDR = _cETHAddr; } function createOrder( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInDAI, uint256 _loanAmountInDAI, bool _orderType ) public returns (CompoundOrder) { require(_compoundTokenAddr != address(0)); CompoundOrder order; address logicContract; if (_compoundTokenAddr != CETH_ADDR) { logicContract = _orderType ? SHORT_CERC20_LOGIC_CONTRACT : LONG_CERC20_LOGIC_CONTRACT; } else { logicContract = _orderType ? SHORT_CEther_LOGIC_CONTRACT : LONG_CEther_LOGIC_CONTRACT; } order = new CompoundOrder(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInDAI, _loanAmountInDAI, _orderType, logicContract, DAI_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CDAI_ADDR, CETH_ADDR); order.transferOwnership(msg.sender); return order; } function getMarketCollateralFactor(address _compoundTokenAddr) public view returns (uint256) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (, uint256 factor) = troll.markets(_compoundTokenAddr); return factor; } } /** * @title The main smart contract of the Betoken hedge fund. * @author Zefram Lou (Zebang Liu) */ contract BetokenFund is BetokenStorage, Utils, TokenController { /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); _; } /** * @notice Passes if the fund is ready for migrating to the next version */ modifier readyForUpgradeMigration { require(hasFinalizedNextVersion == true); require(now > startTimeOfCyclePhase.add(phaseLengths[uint(CyclePhase.Intermission)])); _; } /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * Meta functions */ constructor( address payable _kroAddr, address payable _sTokenAddr, address payable _devFundingAccount, uint256[2] memory _phaseLengths, uint256 _devFundingRate, address payable _previousVersion, address _daiAddr, address payable _kyberAddr, address _compoundFactoryAddr, address _betokenLogic ) public Utils(_daiAddr, _kyberAddr) { controlTokenAddr = _kroAddr; shareTokenAddr = _sTokenAddr; devFundingAccount = _devFundingAccount; phaseLengths = _phaseLengths; devFundingRate = _devFundingRate; cyclePhase = CyclePhase.Manage; compoundFactoryAddr = _compoundFactoryAddr; betokenLogic = _betokenLogic; previousVersion = _previousVersion; cToken = IMiniMeToken(_kroAddr); sToken = IMiniMeToken(_sTokenAddr); } function initTokenListings( address[] memory _kyberTokens, address[] memory _compoundTokens, address[] memory _positionTokens ) public onlyOwner { // May only initialize once require(!hasInitializedTokenListings); hasInitializedTokenListings = true; uint256 i; for (i = 0; i < _kyberTokens.length; i = i.add(1)) { isKyberToken[_kyberTokens[i]] = true; } for (i = 0; i < _compoundTokens.length; i = i.add(1)) { isCompoundToken[_compoundTokens[i]] = true; } for (i = 0; i < _positionTokens.length; i = i.add(1)) { isPositionToken[_positionTokens[i]] = true; } } /** * @notice Used during deployment to set the BetokenProxy contract address. * @param _proxyAddr the proxy's address */ function setProxy(address payable _proxyAddr) public onlyOwner { require(_proxyAddr != address(0)); require(proxyAddr == address(0)); proxyAddr = _proxyAddr; proxy = BetokenProxyInterface(_proxyAddr); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public during(CyclePhase.Intermission) onlyOwner notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.developerInitiateUpgrade.selector, _candidate)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Allows a manager to signal their support of initiating an upgrade. They can change their signal before the end of the Intermission phase. * Managers who oppose initiating an upgrade don't need to call this function, unless they origianlly signalled in support. * Signals are reset every cycle. * @param _inSupport True if the manager supports initiating upgrade, false if the manager opposes it. * @return True if successfully changed signal, false if no changes were made. */ function signalUpgrade(bool _inSupport) public during(CyclePhase.Intermission) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.signalUpgrade.selector, _inSupport)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Allows manager to propose a candidate smart contract for the fund to upgrade to. Among the managers who have proposed a candidate, * the manager with the most voting weight's candidate will be used in the vote. Ties are broken in favor of the larger address. * The proposer may change the candidate they support during the Propose subchunk in their chunk. * @param _chunkNumber the chunk for which the sender is proposing the candidate * @param _candidate the address of the candidate smart contract * @return True if successfully proposed/changed candidate, false otherwise. */ function proposeCandidate(uint256 _chunkNumber, address payable _candidate) public during(CyclePhase.Manage) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.proposeCandidate.selector, _chunkNumber, _candidate)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Allows a manager to vote for or against a candidate smart contract the fund will upgrade to. The manager may change their vote during * the Vote subchunk. A manager who has been a proposer may not vote. * @param _inSupport True if the manager supports initiating upgrade, false if the manager opposes it. * @return True if successfully changed vote, false otherwise. */ function voteOnCandidate(uint256 _chunkNumber, bool _inSupport) public during(CyclePhase.Manage) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.voteOnCandidate.selector, _chunkNumber, _inSupport)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Performs the necessary state changes after a successful vote * @param _chunkNumber the chunk number of the successful vote * @return True if successful, false otherwise */ function finalizeSuccessfulVote(uint256 _chunkNumber) public during(CyclePhase.Manage) notReadyForUpgrade returns (bool _success) { (bool success, bytes memory result) = betokenLogic.delegatecall(abi.encodeWithSelector(this.finalizeSuccessfulVote.selector, _chunkNumber)); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Transfers ownership of Kairo & Share token contracts to the next version. Also updates BetokenFund's * address in BetokenProxy. */ function migrateOwnedContractsToNextVersion() public nonReentrant readyForUpgradeMigration { cToken.transferOwnership(nextVersion); sToken.transferOwnership(nextVersion); proxy.updateBetokenFundAddress(); } /** * @notice Transfers assets to the next version. * @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether. */ function transferAssetToNextVersion(address _assetAddress) public nonReentrant readyForUpgradeMigration isValidToken(_assetAddress) { if (_assetAddress == address(ETH_TOKEN_ADDRESS)) { nextVersion.transfer(address(this).balance); } else { ERC20Detailed token = ERC20Detailed(_assetAddress); token.safeTransfer(nextVersion, token.balanceOf(address(this))); } } /** * Getters */ /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns(uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Returns the length of the user's compound orders array. * @return length of the user's compound orders array */ function compoundOrdersCount(address _userAddr) public view returns(uint256 _count) { return userCompoundOrders[_userAddr].length; } /** * @notice Returns the phaseLengths array. * @return the phaseLengths array */ function getPhaseLengths() public view returns(uint256[2] memory _phaseLengths) { return phaseLengths; } /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in DAI */ function commissionBalanceOf(address _manager) public view returns (uint256 _commission, uint256 _penalty) { if (lastCommissionRedemption[_manager] >= cycleNumber) { return (0, 0); } uint256 cycle = lastCommissionRedemption[_manager] > 0 ? lastCommissionRedemption[_manager] : 1; uint256 cycleCommission; uint256 cyclePenalty; for (; cycle < cycleNumber; cycle = cycle.add(1)) { (cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle); _commission = _commission.add(cycleCommission); _penalty = _penalty.add(cyclePenalty); } } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in DAI */ function commissionOfAt(address _manager, uint256 _cycle) public view returns (uint256 _commission, uint256 _penalty) { if (hasRedeemedCommissionForCycle[_manager][_cycle]) { return (0, 0); } // take risk into account uint256 baseKairoBalance = cToken.balanceOfAt(_manager, managePhaseEndBlock[_cycle.sub(1)]); uint256 baseStake = baseKairoBalance == 0 ? baseRiskStakeFallback[_manager] : baseKairoBalance; if (baseKairoBalance == 0 && baseRiskStakeFallback[_manager] == 0) { return (0, 0); } uint256 riskTakenProportion = riskTakenInCycle[_manager][_cycle].mul(PRECISION).div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold riskTakenProportion = riskTakenProportion > PRECISION ? PRECISION : riskTakenProportion; // max proportion is 1 uint256 fullCommission = totalCommissionOfCycle[_cycle].mul(cToken.balanceOfAt(_manager, managePhaseEndBlock[_cycle])) .div(cToken.totalSupplyAt(managePhaseEndBlock[_cycle])); _commission = fullCommission.mul(riskTakenProportion).div(PRECISION); _penalty = fullCommission.sub(_commission); } /** * Parameter setters */ /** * @notice Changes the address to which the developer fees will be sent. Only callable by owner. * @param _newAddr the new developer fee address */ function changeDeveloperFeeAccount(address payable _newAddr) public onlyOwner { require(_newAddr != address(0) && _newAddr != address(this)); devFundingAccount = _newAddr; } /** * @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner. * @param _newProp the new proportion, fixed point decimal */ function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner { require(_newProp < PRECISION); require(_newProp < devFundingRate); devFundingRate = _newProp; } /** * @notice Allows managers to invest in a token. Only callable by owner. * @param _token address of the token to be listed */ function listKyberToken(address _token) public onlyOwner { isKyberToken[_token] = true; } /** * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.nextPhase.selector)); if (!success) { revert(); } } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using DAI as payment. The more one pays, the more Kairo one gets. * There's a max Kairo amount that can be bought, and excess payment will be sent back to sender. * @param _donationInDAI the amount of DAI to be used for registration */ function registerWithDAI(uint256 _donationInDAI) public nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.registerWithDAI.selector, _donationInDAI)); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more Kairo one gets. * There's a max Kairo amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.registerWithETH.selector)); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more Kairo one gets. * There's a max Kairo amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.registerWithToken.selector, _token, _donationInTokens)); if (!success) { revert(); } } /** * Intermission phase functions */ /** * @notice Deposit Ether into the fund. Ether will be converted into DAI. */ function depositEther() public payable during(CyclePhase.Intermission) nonReentrant notReadyForUpgrade { // Buy DAI with ETH uint256 actualDAIDeposited; uint256 actualETHDeposited; (,, actualDAIDeposited, actualETHDeposited) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, dai); // Send back leftover ETH uint256 leftOverETH = msg.value.sub(actualETHDeposited); if (leftOverETH > 0) { msg.sender.transfer(leftOverETH); } // Register investment __deposit(actualDAIDeposited); // Emit event emit Deposit(cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHDeposited, actualDAIDeposited, now); } /** * @notice Deposit DAI Stablecoin into the fund. * @param _daiAmount The amount of DAI to be deposited. May be different from actual deposited amount. */ function depositDAI(uint256 _daiAmount) public during(CyclePhase.Intermission) nonReentrant notReadyForUpgrade { dai.safeTransferFrom(msg.sender, address(this), _daiAmount); // Register investment __deposit(_daiAmount); // Emit event emit Deposit(cycleNumber, msg.sender, DAI_ADDR, _daiAmount, _daiAmount, now); } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into DAI. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. */ function depositToken(address _tokenAddr, uint256 _tokenAmount) public nonReentrant during(CyclePhase.Intermission) isValidToken(_tokenAddr) notReadyForUpgrade { require(_tokenAddr != DAI_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)); ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransferFrom(msg.sender, address(this), _tokenAmount); // Convert token into DAI uint256 actualDAIDeposited; uint256 actualTokenDeposited; (,, actualDAIDeposited, actualTokenDeposited) = __kyberTrade(token, _tokenAmount, dai); // Give back leftover tokens uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited); if (leftOverTokens > 0) { token.safeTransfer(msg.sender, leftOverTokens); } // Register investment __deposit(actualDAIDeposited); // Emit event emit Deposit(cycleNumber, msg.sender, _tokenAddr, actualTokenDeposited, actualDAIDeposited, now); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInDAI Amount of funds to be withdrawn expressed in DAI. Fixed-point decimal. May be different from actual amount. */ function withdrawEther(uint256 _amountInDAI) public during(CyclePhase.Intermission) nonReentrant { // Buy ETH uint256 actualETHWithdrawn; uint256 actualDAIWithdrawn; (,, actualETHWithdrawn, actualDAIWithdrawn) = __kyberTrade(dai, _amountInDAI, ETH_TOKEN_ADDRESS); __withdraw(actualDAIWithdrawn); // Transfer Ether to user msg.sender.transfer(actualETHWithdrawn); // Emit event emit Withdraw(cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHWithdrawn, actualDAIWithdrawn, now); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInDAI Amount of funds to be withdrawn expressed in DAI. Fixed-point decimal. May be different from actual amount. */ function withdrawDAI(uint256 _amountInDAI) public during(CyclePhase.Intermission) nonReentrant { __withdraw(_amountInDAI); // Transfer DAI to user dai.safeTransfer(msg.sender, _amountInDAI); // Emit event emit Withdraw(cycleNumber, msg.sender, DAI_ADDR, _amountInDAI, _amountInDAI, now); } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInDAI The amount of funds to be withdrawn expressed in DAI. Fixed-point decimal. May be different from actual amount. */ function withdrawToken(address _tokenAddr, uint256 _amountInDAI) public nonReentrant during(CyclePhase.Intermission) isValidToken(_tokenAddr) { require(_tokenAddr != DAI_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)); ERC20Detailed token = ERC20Detailed(_tokenAddr); // Convert DAI into desired tokens uint256 actualTokenWithdrawn; uint256 actualDAIWithdrawn; (,, actualTokenWithdrawn, actualDAIWithdrawn) = __kyberTrade(dai, _amountInDAI, token); __withdraw(actualDAIWithdrawn); // Transfer tokens to user token.safeTransfer(msg.sender, actualTokenWithdrawn); // Emit event emit Withdraw(cycleNumber, msg.sender, _tokenAddr, actualTokenWithdrawn, actualDAIWithdrawn, now); } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __redeemCommission(); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit(cycleNumber, msg.sender, DAI_ADDR, commission, commission, now); } else { // Transfer the commission in DAI dai.safeTransfer(msg.sender, commission); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in Betoken Shares, false to redeem in DAI * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __redeemCommissionForCycle(_cycle); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit(cycleNumber, msg.sender, DAI_ADDR, commission, commission, now); } else { // Transfer the commission in DAI dai.safeTransfer(msg.sender, commission); } } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold */ function sellLeftoverToken(address _tokenAddr) public nonReentrant during(CyclePhase.Intermission) isValidToken(_tokenAddr) { ERC20Detailed token = ERC20Detailed(_tokenAddr); (,,uint256 actualDAIReceived,) = __kyberTrade(token, getBalance(token, address(this)), dai); totalFundsInDAI = totalFundsInDAI.add(actualDAIReceived); } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public nonReentrant during(CyclePhase.Intermission) { // Load order info require(_orderAddress != address(0)); CompoundOrder order = CompoundOrder(_orderAddress); require(order.isSold() == false && order.cycleNumber() < cycleNumber); // Sell short order // Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract uint256 beforeDAIBalance = dai.balanceOf(address(this)); order.sellOrder(0, MAX_QTY); uint256 actualDAIReceived = dai.balanceOf(address(this)).sub(beforeDAIBalance); totalFundsInDAI = totalFundsInDAI.add(actualDAIReceived); } /** * @notice Burns the Kairo balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose Kairo balance will be burned */ function burnDeadman(address _deadman) public nonReentrant during(CyclePhase.Intermission) { require(_deadman != address(this)); require(cycleNumber.sub(lastActiveCycle[_deadman]) >= INACTIVE_THRESHOLD); require(cToken.destroyTokens(_deadman, cToken.balanceOf(_deadman))); } /** * Manage phase functions */ /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of Kairos to be staked in support of the investment * @param _minPrice the minimum price for the trade * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public nonReentrant isValidToken(_tokenAddress) during(CyclePhase.Manage) { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.createInvestment.selector, _tokenAddress, _stake, _minPrice, _maxPrice)); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked Kairo plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade * @param _maxPrice the maximum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.sellInvestmentAsset.selector, _investmentId, _tokenAmount, _minPrice, _maxPrice)); if (!success) { revert(); } } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of Kairos to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public nonReentrant during(CyclePhase.Manage) isValidToken(_tokenAddress) { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.createCompoundOrder.selector, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice)); if (!success) { revert(); } } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.sellCompoundOrder.selector, _orderId, _minPrice, _maxPrice)); if (!success) { revert(); } } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInDAI amount of DAI to use for repaying debt */ function repayCompoundOrder(uint256 _orderId, uint256 _repayAmountInDAI) public during(CyclePhase.Manage) nonReentrant { (bool success,) = betokenLogic.delegatecall(abi.encodeWithSelector(this.repayCompoundOrder.selector, _orderId, _repayAmountInDAI)); if (!success) { revert(); } } /** * Internal use functions */ // MiniMe TokenController functions, not used right now /** * @notice Called when `_owner` sends ether to the MiniMe Token contract * @param _owner The address that sent the ether to create tokens * @return True if the ether is accepted, false if it throws */ function proxyPayment(address _owner) public payable returns(bool) { return false; } /** * @notice Notifies the controller about a token transfer allowing the * controller to react if desired * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint _amount) public returns(bool) { return true; } /** * @notice Notifies the controller about an approval allowing the * controller to react if desired * @param _owner The address that calls `approve()` * @param _spender The spender in the `approve()` call * @param _amount The amount in the `approve()` call * @return False if the controller does not authorize the approval */ function onApprove(address _owner, address _spender, uint _amount) public returns(bool) { return true; } /** * @notice Handles deposits by minting Betoken Shares & updating total funds. * @param _depositDAIAmount The amount of the deposit in DAI */ function __deposit(uint256 _depositDAIAmount) internal { // Register investment and give shares if (sToken.totalSupply() == 0 || totalFundsInDAI == 0) { require(sToken.generateTokens(msg.sender, _depositDAIAmount)); } else { require(sToken.generateTokens(msg.sender, _depositDAIAmount.mul(sToken.totalSupply()).div(totalFundsInDAI))); } totalFundsInDAI = totalFundsInDAI.add(_depositDAIAmount); } /** * @notice Handles deposits by burning Betoken Shares & updating total funds. * @param _withdrawDAIAmount The amount of the withdrawal in DAI */ function __withdraw(uint256 _withdrawDAIAmount) internal { // Burn Shares require(sToken.destroyTokens(msg.sender, _withdrawDAIAmount.mul(sToken.totalSupply()).div(totalFundsInDAI))); totalFundsInDAI = totalFundsInDAI.sub(_withdrawDAIAmount); } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __redeemCommission() internal returns (uint256 _commission) { require(lastCommissionRedemption[msg.sender] < cycleNumber); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for (uint256 i = lastCommissionRedemption[msg.sender]; i < cycleNumber; i = i.add(1)) { hasRedeemedCommissionForCycle[msg.sender][i] = true; } lastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle[cycleNumber].add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __redeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!hasRedeemedCommissionForCycle[msg.sender][_cycle]); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionOfAt(msg.sender, _cycle); hasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle[cycleNumber].add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(_cycle, msg.sender, _commission); } function() external payable {} }
The amount of funds held by the fund.
uint256 public totalFundsInDAI;
14,018,472
[ 1, 1986, 3844, 434, 284, 19156, 15770, 635, 326, 284, 1074, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 2078, 42, 19156, 382, 9793, 45, 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 ]
./full_match/44787/0xB39A777c6E3AE43e630621bC144Ce9bd6DcC344e/sources/src/Sway.sol
* @dev Gets the token uri @return string representing the token uri/
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Sway: URI query for nonexistent token"); uint256 eventId = tokenEvent[tokenId]; return string(abi.encodePacked(_baseURI(), eventId.toString(), "/", tokenId.toString(), _baseURIExtension)); }
13,242,752
[ 1, 3002, 326, 1147, 2003, 327, 533, 5123, 326, 1147, 2003, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 55, 1888, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 203, 3639, 2254, 5034, 26004, 273, 1147, 1133, 63, 2316, 548, 15533, 203, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 24899, 1969, 3098, 9334, 26004, 18, 10492, 9334, 2206, 3113, 1147, 548, 18, 10492, 9334, 389, 1969, 3098, 3625, 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 ]
./full_match/1/0x63ac91D179aFb27D0730E781a2461eb14aEeE010/sources/negative-entropy/NegativeEntropy.sol
* @dev Remove a seed from the set only/
function removeSeed(bytes32 seedHash) internal returns (bool) { return seedSet.remove(seedHash); }
8,361,296
[ 1, 3288, 279, 5009, 628, 326, 444, 1338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 12702, 12, 3890, 1578, 5009, 2310, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 327, 5009, 694, 18, 4479, 12, 12407, 2310, 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 ]
./partial_match/3/0xFD58D3cEbcD3c1DbaB02C8F18AfF24C1E757406F/sources/FixedSupplyToken.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract FixedSupplyToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public amount_eth; uint8 public token_price; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "DGC"; name = "Token DIGHCOIN para Jogos"; decimals = 18; amount_eth = 150; token_price = 100; _totalSupply = 1000000 * 10**uint(decimals); balances[owner] = _totalSupply * 5 / 100; balances[address(this)] = _totalSupply * 95 / 100; emit Transfer(address(0), address(this), _totalSupply * 95 / 100); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { require(msg.value > 0); require(balances[address(this)] > msg.value * token_price); amount_eth += msg.value; uint tokens = msg.value * token_price; balances[address(this)] -= tokens; balances[msg.sender] += tokens; emit Transfer(address(this), msg.sender, tokens); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
5,199,960
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 392, 2172, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 15038, 3088, 1283, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 3844, 67, 546, 31, 203, 565, 2254, 28, 1071, 1147, 67, 8694, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 40, 15396, 14432, 203, 3639, 508, 273, 315, 1345, 463, 16055, 3865, 706, 12602, 804, 717, 538, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 3844, 67, 546, 273, 18478, 31, 203, 3639, 1147, 67, 8694, 273, 2130, 31, 203, 540, 203, 3639, 389, 4963, 3088, 1283, 273, 15088, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 540, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 380, 1381, 342, 2130, 31, 203, 3639, 324, 26488, 63, 2867, 12, 2211, 25887, 273, 389, 4963, 3088, 1283, 380, 16848, 342, 2130, 31, 203, 540, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1758, 12, 2211, 3631, 389, 4963, 3088, 1283, 380, 16848, 342, 2130, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import "./interface/StakingARMInterface.sol"; contract StakingARM is StakingARMInterface{ //Owner address address owner; //User variables mapping(address => uint256) stakingBalance; //User's staked ARM token mapping(address => uint256) rewardBalanceOf; //User's distributed reward from vault which 'NOT YET' claim mapping(address => bool) hasStaked; //this variable check if the user used to stake in the vault to prevent duplication of 'stakers[]'. mapping(address => bool) isStaking; //Staking status of individual address, FALSE if balance = 0 address[] stakers; //Address of stakers for rewarding reason //Vault variables manipulation uint256 accRewardPerShare; // spending reward RATE per share :: calculate from TotalRewardRemaining / TotalStakingToken / rewardSpendingDuration uint256 rewardSpendingDuration; // Duration in days that the reward will be distributed // RewardSpendingDuration is the CONSTANT that indicate the RATE of the current reward will be distributed if no-one is updating the vault // Everytime that users stake/unstake/claimReward, the spending rate (accRewardPerShare) will be re-calculated uint256 lastRewardTimestamp; //Index of current updated rewardblock (blocktime) //This code is modified from Masterchef contract // Whenever a user stake or unstake to the vault. // 1. The 'rewardBalance' (and `lastRewardTimestamp`) gets updated. // 2. User receives the 'rewardBalanceOf' sent to his/her address. (rewardBalanceOf then set to 0) // 3. User's `stakingBalance` gets updated. // 4. User's `rewardBalanceOf` gets updated. IERC20 public armToken; // ARM token OR LP-token to be staked IERC20 public rewardToken; // BUSD token //Set object of ARM to armToken and object of BUSD to rewardToken when the contract is deployed. constructor(IERC20 importARMToken, IERC20 importRewardToken){ armToken = importARMToken; // This can be LP token when deploying contract rewardToken = importRewardToken; owner = msg.sender; rewardSpendingDuration = 30 days; // set default is 30 days lastRewardTimestamp = block.timestamp; locked = false; } error TransferFail(); event Stake(address _staker, uint _amount); event Unstake(address _unstaker, uint _amount); event ClaimReward(address _claimer, uint _amount); event EmergencyWithdraw(address _withdrawer, uint _amount); event SetRewardSpendingDuration(uint OldDuration, uint NewDuration); event SetNewOwner(address OldOwner, address NewOwner); modifier onlyOwner { require(msg.sender == owner); _; } bool internal locked; modifier reentrancyGuard { require(!locked); locked = true; // lock the re-entrancy before contract execution _; locked = false; // unlock when finish } //-------------------------------------- //------Reading parameters function----- //-------------------------------------- //Get the ARM staking for each requested address function manualGetStakingBalance(address _staker) view public returns(uint256) { return stakingBalance[_staker]; } //Get the reward balance of each requested address (this included the pending update reward) function manualGetRewardBalance(address _staker) view public returns(uint256) { uint256 deltaTime = block.timestamp - lastRewardTimestamp; if(deltaTime > rewardSpendingDuration){ deltaTime = rewardSpendingDuration; } uint256 pendingReward = deltaTime * accRewardPerShare * stakingBalance[_staker]; uint256 totalReward = rewardBalanceOf[_staker] + pendingReward; return totalReward; } //Get the owner address function getOwner() view public returns(address){ return owner; } function getAccRewardPerShare() view public returns(uint) { return accRewardPerShare; } function getLastRewardTimestamp() view public returns(uint){ return lastRewardTimestamp; } function getStakingBalance(address user) view public returns(uint){ return stakingBalance[user]; } //Get the BUSD balance in vault function getVaultBalance() public view returns(uint256){ return rewardToken.balanceOf(address(this)); } //Get the ARM balance in vault function getTotalStakedARM() public view returns(uint256){ return armToken.balanceOf(address(this)); } //Get Total reward pending to be claim function getTotalRewardPending() internal view returns(uint256){ address[] memory varsStaker = stakers; //get stakers to local memory vars to minimalize gas spend in for loop uint256 numberUser = varsStaker.length; uint256 totalreward; for(uint i = 0; i< numberUser; i++){ totalreward += rewardBalanceOf[varsStaker[i]]; } return totalreward; } //Get remaining reward function getRewardRemaining() public view returns(uint256) { return (getVaultBalance() - getTotalRewardPending()); } //Reward spending duration return in blocktime function getRewardSpendingDuration() public view returns(uint256) { return rewardSpendingDuration; } function getRewardBalanceOf(address user) public view returns(uint256) { return rewardBalanceOf[user]; } //------------------------------------------------- //--------------Action function-------------------- //------------------------------------------------- function updateRewardBlock() internal{ //If the lastRewardTimestamp is updated. No need for update if(block.timestamp <= lastRewardTimestamp){ return; } uint256 totalStakedARM = getTotalStakedARM(); //The ARM balance in vault contract //Check if this is the first staker then start the block reward here if(totalStakedARM == 0){ lastRewardTimestamp = block.timestamp; return; } uint256 remainingReward = getRewardRemaining(); //Check if rewardPool is empty if(remainingReward == 0){ return; } //Check if the reward block not update for long time (more than the rewardSpendingDuration) //then deltaTime to be calculate should be equal to MAX (rewardSpendingDuration) uint256 deltaTime = block.timestamp - lastRewardTimestamp; if(deltaTime > rewardSpendingDuration){ deltaTime = rewardSpendingDuration; } uint i; uint gainReward; address[] memory varsStaker = stakers; // gas optimization for (i=0 ; i< varsStaker.length ; i++){ //gainReward is 1e18 :: e18*e18*uint / 1e18 gainReward = stakingBalance[varsStaker[i]] * accRewardPerShare * deltaTime / 1e18; rewardBalanceOf[varsStaker[i]] += gainReward; } lastRewardTimestamp = block.timestamp; } function manualUpdateRewardBlock() external reentrancyGuard{ updateRewardBlock(); } function stakeARM(uint _amount) external reentrancyGuard { //Check the amount and balance of staker require(_amount > 0, "Staking amount must greater than zero"); require(armToken.balanceOf(msg.sender)>=_amount, "Not enough ARM token to be deposited."); //1. update the reward vault to get lastRewardTimestamp //2. claim the pending reward //3. stake the ARM token //4. update accRewardPerShare = totalRemainingBalance / totalStakingBalance / rewardSpendingDuration updateRewardBlock(); bool success; if(rewardBalanceOf[msg.sender]>0){ uint256 toBePaid = rewardBalanceOf[msg.sender]; rewardBalanceOf[msg.sender]=0; success = rewardToken.transfer(msg.sender, toBePaid); if(!success){ revert TransferFail(); } emit ClaimReward(msg.sender, toBePaid); } //Transfer ARM to contract address then update balance success = armToken.transferFrom(msg.sender,address(this),_amount); if(!success){ revert TransferFail(); } stakingBalance[msg.sender] += _amount; //add staker address to the arrays for rewarding reasons if(!hasStaked[msg.sender]){ stakers.push(msg.sender); hasStaked[msg.sender] = true; } //Currently staking isStaking[msg.sender] = true; //Update accRewardPerShare uint256 totalRemainingBalance = getRewardRemaining(); uint256 totalStakingBalance = getTotalStakedARM(); // newAccRewardPerShare is 1e18 :: e18 * 1e18 / e18 / uint uint256 newAccRewardPerShare = (totalRemainingBalance * 1e18 / totalStakingBalance) / rewardSpendingDuration; accRewardPerShare = newAccRewardPerShare; emit Stake(msg.sender, _amount); } function manualClaimReward() external reentrancyGuard{ updateRewardBlock(); require(getRewardRemaining() >= rewardBalanceOf[msg.sender],"Not enough reward in pool."); if(rewardBalanceOf[msg.sender]>0){ uint256 toBePaid = rewardBalanceOf[msg.sender]; rewardBalanceOf[msg.sender]=0; //set balance to 0 before transfer to double prevent reentrancy guard bool success = rewardToken.transfer(msg.sender, toBePaid); if(!success){ revert TransferFail(); } emit ClaimReward(msg.sender, toBePaid); } } function unstakeARM(uint _amount) external reentrancyGuard{ //Check the amount and balancer of unstaker require(_amount > 0, "Unstaking amount must greater than zero"); require(stakingBalance[msg.sender] >= _amount, "Not enough ARM token to be withdrawed."); //1. update the reward vault to get lastRewardTimestamp //2. claim the pending reward //3. unstake the ARM token //4. update accRewardPerShare = totalRemainingBalance / totalStakingBalance / rewardSpendingDuration updateRewardBlock(); bool success; if(rewardBalanceOf[msg.sender]>0){ success = rewardToken.transfer(msg.sender, rewardBalanceOf[msg.sender]); if(!success){ revert TransferFail(); } emit ClaimReward(msg.sender, rewardBalanceOf[msg.sender]); rewardBalanceOf[msg.sender]=0; } //Transfer ARM to unstaker success = armToken.transfer(msg.sender,_amount); //calculate balance after transfer stakingBalance[msg.sender] -= _amount; if(stakingBalance[msg.sender]==0){ isStaking[msg.sender] = false; } //Update accRewardPerShare uint256 totalRemainingBalance = getRewardRemaining(); uint256 totalStakingBalance = getTotalStakedARM(); //if totalStakiingBalance = 0 --> no ARM in vault = no reward then accRewardPerShare = 0 if(totalStakingBalance==0) { accRewardPerShare = 0; } else { // accRewardPerShare is 1e18 :: e18 * 1e18 / e18 / uint accRewardPerShare = (totalRemainingBalance * 1e18 /totalStakingBalance) / rewardSpendingDuration; } emit Unstake(msg.sender,_amount); } //Set reward duration only Owner can access function _setRewardDurationSpending (uint hour) external onlyOwner { updateRewardBlock(); //update distribute reward before uint OldDuration = rewardSpendingDuration; uint NewDuration = hour * 60 * 60; // Input in 'hour', Stored in Seconds rewardSpendingDuration = NewDuration; accRewardPerShare = (getRewardRemaining() * 1e18 / getTotalStakedARM()) / NewDuration; // update the distribution RATE emit SetRewardSpendingDuration(OldDuration, NewDuration); } //Set new admin function _transferOwnership (address newOwner) external onlyOwner { address oldOwner = owner; owner = newOwner; emit SetNewOwner(oldOwner, newOwner); } //Withdraw ARM token without caring reward function emergencyWithdraw() external reentrancyGuard { uint withdrawBl = stakingBalance[msg.sender]; isStaking[msg.sender] = false; rewardBalanceOf[msg.sender] = 0; stakingBalance[msg.sender] = 0; armToken.transfer(msg.sender, withdrawBl); emit EmergencyWithdraw(msg.sender, withdrawBl); } }
Get the ARM balance in vault
function getTotalStakedARM() public view returns(uint256){ return armToken.balanceOf(address(this)); }
1,086,184
[ 1, 967, 326, 6052, 49, 11013, 316, 9229, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12831, 510, 9477, 26120, 1435, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 23563, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-10-02 */ /** * This code is inspired by BOMB, Sparta and AHF. * Unlike other DeFi projects out there, it proposes a balanced reward and burn function. Each transaction burns a variable MTON quantity * depending on the total supply remaining on the blockchain. The same value is placed in reward for distribution to top holders. */ pragma solidity ^0.5.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } 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 name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } //modified for decimals from uint8 to uint256 function decimals() public view returns(uint256) { return _decimals; } } contract MarathonToken is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "Marathon.Finance"; string constant tokenSymbol = "MTON"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 490 * (10 ** 18); uint256 public basePercent = 500; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function findPercent(uint256 value) public view returns (uint256) { uint256 percent = 0; if ((_totalSupply > 400 * (10 ** 18)) && (_totalSupply <= 490 * (10 ** 18))) { percent = value.mul(500).div(10000); } if ((_totalSupply > 300 * (10 ** 18)) && (_totalSupply <= 400 * (10 ** 18))) { percent = value.mul(400).div(10000); } if ((_totalSupply > 200 * (10 ** 18)) && (_totalSupply <= 300 * (10 ** 18))) { percent = value.mul(300).div(10000); } if ((_totalSupply > 100 * (10 ** 18)) && (_totalSupply <= 200 * (10 ** 18))) { percent = value.mul(200).div(10000); } if ((_totalSupply > 42 * (10 ** 18)) && (_totalSupply <= 100 * (10 ** 18))) { percent = value.mul(100).div(10000); } if (_totalSupply <= 42 * (10 ** 18)) { percent = 0; } return percent.div(2); } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = findPercent(value); uint256 tokensToReward = findPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn.add(tokensToReward)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); //burn _balances[0x0000000000000000000000000000000000000000] = _balances[0x0000000000000000000000000000000000000000].add(tokensToBurn); //reward _balances[0xaDd3D05E9fa8c109D8D314eE977c7f805b31945D] = _balances[0xaDd3D05E9fa8c109D8D314eE977c7f805b31945D].add(tokensToReward); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); // burns to the address if (tokensToBurn>0){ emit Transfer(msg.sender, 0x0000000000000000000000000000000000000000, tokensToBurn); } // send to reward address if (tokensToBurn>0){ emit Transfer(msg.sender, 0xaDd3D05E9fa8c109D8D314eE977c7f805b31945D, tokensToReward); } return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } 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); uint256 tokensToBurn = findPercent(value); uint256 tokensToReward = findPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn.add(tokensToReward)); _balances[to] = _balances[to].add(tokensToTransfer); _balances[0x0000000000000000000000000000000000000000] = _balances[0x0000000000000000000000000000000000000000].add(tokensToBurn); _balances[0xaDd3D05E9fa8c109D8D314eE977c7f805b31945D] = _balances[0xaDd3D05E9fa8c109D8D314eE977c7f805b31945D].add(tokensToReward); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); //burn token if (tokensToBurn>0) { emit Transfer(from, 0x0000000000000000000000000000000000000000, tokensToBurn); } //reward if (tokensToReward>0) { emit Transfer(from, 0xaDd3D05E9fa8c109D8D314eE977c7f805b31945D, tokensToReward); } return true; } 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; } 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; } function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
modified for decimals from uint8 to uint256
function decimals() public view returns(uint256) { return _decimals; }
282,951
[ 1, 7342, 364, 15105, 628, 2254, 28, 358, 2254, 5034, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 15105, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 565, 327, 389, 31734, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xa325B403408e8443eD69fe2047467025C5A9C3f9/sources/HybridFarmBSC.sol
Run end round function if round is overAdjust pharaohReqMake sure player fits requirementRemove snailsAdjust msg.sender claimed dividendsAdd 8 minutes to timerpharaohReq becomes the amount of Hybrids sacrificed + 40msg.sender becomes new Pharaoh
function BecomePharaoh(uint256 _snails) public { require(gameStarted == true, "game hasn't started yet"); require(hatcherySnail[msg.sender] >= _snails, "not enough Hybrid in hatchery"); if(now >= godTimer) { AscendGod(); } if(pharaohReq < _snailsToRemove){ pharaohReq = PHARAOH_REQ_START; pharaohReq = pharaohReq.sub(_snailsToRemove); if(pharaohReq < PHARAOH_REQ_START){ pharaohReq = PHARAOH_REQ_START; } } if(_snails >= pharaohReq) { maxSnail = maxSnail.sub(_snails); hatcherySnail[msg.sender] = hatcherySnail[msg.sender].sub(_snails); claimedDivs[msg.sender] = claimedDivs[msg.sender].sub(_snails.mul(divsPerSnail)); godTimer = godTimer.add(GOD_TIMER_BOOST); pharaohReq = _snails.add(PHARAOH_REQ_START); pharaoh = msg.sender; emit BecamePharaoh(msg.sender, godRound); } }
11,097,897
[ 1, 1997, 679, 3643, 445, 309, 3643, 353, 1879, 10952, 24867, 6033, 76, 6113, 6464, 3071, 7291, 13351, 12405, 3288, 4556, 15208, 10952, 1234, 18, 15330, 7516, 329, 3739, 350, 5839, 986, 1725, 6824, 358, 5441, 844, 297, 6033, 76, 6113, 12724, 326, 3844, 434, 14881, 14400, 87, 20071, 86, 704, 3263, 397, 8063, 3576, 18, 15330, 12724, 394, 4360, 297, 6033, 76, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 557, 1742, 3731, 297, 6033, 76, 12, 11890, 5034, 389, 87, 6025, 87, 13, 1071, 288, 203, 3639, 2583, 12, 13957, 9217, 422, 638, 16, 315, 13957, 13342, 1404, 5746, 4671, 8863, 203, 3639, 2583, 12, 76, 505, 627, 55, 6025, 63, 3576, 18, 15330, 65, 1545, 389, 87, 6025, 87, 16, 315, 902, 7304, 14881, 14400, 316, 366, 505, 627, 8863, 203, 540, 203, 3639, 309, 12, 3338, 1545, 314, 369, 6777, 13, 288, 203, 5411, 22475, 409, 43, 369, 5621, 203, 3639, 289, 203, 540, 203, 540, 203, 540, 203, 540, 203, 3639, 309, 12, 844, 297, 6033, 76, 6113, 411, 389, 87, 6025, 11634, 3288, 15329, 203, 5411, 24867, 6033, 76, 6113, 273, 15490, 985, 20463, 44, 67, 20373, 67, 7570, 31, 203, 5411, 24867, 6033, 76, 6113, 273, 24867, 6033, 76, 6113, 18, 1717, 24899, 87, 6025, 11634, 3288, 1769, 203, 5411, 309, 12, 844, 297, 6033, 76, 6113, 411, 15490, 985, 20463, 44, 67, 20373, 67, 7570, 15329, 203, 7734, 24867, 6033, 76, 6113, 273, 15490, 985, 20463, 44, 67, 20373, 67, 7570, 31, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 3639, 309, 24899, 87, 6025, 87, 1545, 24867, 6033, 76, 6113, 13, 288, 203, 2398, 203, 5411, 943, 55, 6025, 273, 943, 55, 6025, 18, 1717, 24899, 87, 6025, 87, 1769, 203, 5411, 366, 505, 627, 55, 6025, 63, 3576, 18, 15330, 65, 273, 366, 505, 627, 55, 6025, 63, 3576, 18, 15330, 8009, 1717, 24899, 87, 6025, 87, 1769, 203, 2398, 203, 2 ]
./partial_match/1/0x15dE97DA354c26fb896f1B6C8eD08Bde7CE06046/sources/LnFeeSystem.sol
@dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with GSN meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } uint256[50] private __gap; }
2,623,985
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 10784, 429, 353, 10188, 6934, 288, 203, 565, 445, 1001, 1042, 67, 2738, 1435, 2713, 12562, 288, 203, 3639, 1001, 1042, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 289, 203, 203, 203, 565, 445, 1001, 1042, 67, 2738, 67, 4384, 8707, 1435, 2713, 12562, 2618, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 63, 3361, 65, 3238, 1001, 14048, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x9906464A23A312D945FC1eA24Ec499A4B140b99C/sources/src/router/Router.sol
@notice view function to see if a token has permission to swap using the router.
function permissionGranted(address token) external view returns (bool) { return permission[token]; }
11,559,141
[ 1, 1945, 445, 358, 2621, 309, 279, 1147, 711, 4132, 358, 7720, 1450, 326, 4633, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4132, 14570, 12, 2867, 1147, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 4132, 63, 2316, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/ComptrollerInterface.sol pragma solidity 0.5.17; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } // File: contracts/InterestRateModel.sol pragma solidity 0.5.17; /** * @title InterestRateModel Interface */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } // File: contracts/GTokenInterfaces.sol pragma solidity 0.5.17; contract GTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-gToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract GTokenInterface is GTokenStorage { /** * @notice Indicator that this is a GToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Interface { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } // File: contracts/ErrorReporter.sol pragma solidity 0.5.17; contract ComptrollerErrorReporter { enum Error { NO_ERROR, // 0 UNAUTHORIZED, // 1 COMPTROLLER_MISMATCH, // 2 INSUFFICIENT_SHORTFALL, // 3 INSUFFICIENT_LIQUIDITY, // 4 INVALID_CLOSE_FACTOR, // 5 INVALID_COLLATERAL_FACTOR, // 6 INVALID_LIQUIDATION_INCENTIVE, // 7 MARKET_NOT_ENTERED, // 8 no longer possible MARKET_NOT_LISTED, // 9 MARKET_ALREADY_LISTED, // 10 MATH_ERROR, // 11 NONZERO_BORROW_BALANCE, // 12 PRICE_ERROR, // 13 REJECTION, // 14 SNAPSHOT_ERROR, // 15 TOO_MANY_ASSETS, // 16 TOO_MUCH_REPAY // 17 } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0 ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, // 1 EXIT_MARKET_BALANCE_OWED, // 2 EXIT_MARKET_REJECTION, // 3 SET_CLOSE_FACTOR_OWNER_CHECK, // 4 SET_CLOSE_FACTOR_VALIDATION, // 5 SET_COLLATERAL_FACTOR_OWNER_CHECK, // 6 SET_COLLATERAL_FACTOR_NO_EXISTS, // 7 SET_COLLATERAL_FACTOR_VALIDATION, // 8 SET_COLLATERAL_FACTOR_WITHOUT_PRICE, // 9 SET_IMPLEMENTATION_OWNER_CHECK, // 10 SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, // 11 SET_LIQUIDATION_INCENTIVE_VALIDATION, // 12 SET_MAX_ASSETS_OWNER_CHECK, // 13 SET_PENDING_ADMIN_OWNER_CHECK, // 14 SET_PENDING_IMPLEMENTATION_OWNER_CHECK, // 15 SET_PRICE_ORACLE_OWNER_CHECK, // 16 SUPPORT_MARKET_EXISTS, // 17 SUPPORT_MARKET_OWNER_CHECK, // 18 SET_PAUSE_GUARDIAN_OWNER_CHECK // 19 } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, // 0 UNAUTHORIZED, // 1 BAD_INPUT, // 2 COMPTROLLER_REJECTION, // 3 COMPTROLLER_CALCULATION_ERROR, // 4 INTEREST_RATE_MODEL_ERROR, // 5 INVALID_ACCOUNT_PAIR, // 6 INVALID_CLOSE_AMOUNT_REQUESTED, // 7 INVALID_COLLATERAL_FACTOR, // 8 MATH_ERROR, // 9 MARKET_NOT_FRESH, // 10 MARKET_NOT_LISTED, // 11 TOKEN_INSUFFICIENT_ALLOWANCE, // 12 TOKEN_INSUFFICIENT_BALANCE, // 13 TOKEN_INSUFFICIENT_CASH, // 14 TOKEN_TRANSFER_IN_FAILED, // 15 TOKEN_TRANSFER_OUT_FAILED // 16 } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0 ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, // 1 ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, // 2 ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, // 3 ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, // 4 ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, // 5 ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, // 6 BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, // 7 BORROW_ACCRUE_INTEREST_FAILED, // 8 BORROW_CASH_NOT_AVAILABLE, // 9 BORROW_FRESHNESS_CHECK, // 10 BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 11 BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, // 12 BORROW_MARKET_NOT_LISTED, // 13 BORROW_COMPTROLLER_REJECTION, // 14 LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, // 15 LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, // 16 LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, // 17 LIQUIDATE_COMPTROLLER_REJECTION, // 18 LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, // 19 LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, // 20 LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, // 21 LIQUIDATE_FRESHNESS_CHECK, // 22 LIQUIDATE_LIQUIDATOR_IS_BORROWER, // 23 LIQUIDATE_REPAY_BORROW_FRESH_FAILED, // 24 LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, // 25 LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, // 26 LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, // 27 LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, // 28 LIQUIDATE_SEIZE_TOO_MUCH, // 29 MINT_ACCRUE_INTEREST_FAILED, // 30 MINT_COMPTROLLER_REJECTION, // 31 MINT_EXCHANGE_CALCULATION_FAILED, // 32 MINT_EXCHANGE_RATE_READ_FAILED, // 33 MINT_FRESHNESS_CHECK, // 34 MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 35 MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 36 MINT_TRANSFER_IN_FAILED, // 37 MINT_TRANSFER_IN_NOT_POSSIBLE, // 38 REDEEM_ACCRUE_INTEREST_FAILED, // 39 REDEEM_COMPTROLLER_REJECTION, // 40 REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, // 41 REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, // 42 REDEEM_EXCHANGE_RATE_READ_FAILED, // 42 REDEEM_FRESHNESS_CHECK, // 43 REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 44 REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 45 REDEEM_TRANSFER_OUT_NOT_POSSIBLE, // 46 REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, // 47 REDUCE_RESERVES_ADMIN_CHECK, // 48 REDUCE_RESERVES_CASH_NOT_AVAILABLE, // 49 REDUCE_RESERVES_FRESH_CHECK, // 50 REDUCE_RESERVES_VALIDATION, // 51 REPAY_BEHALF_ACCRUE_INTEREST_FAILED, // 52 REPAY_BORROW_ACCRUE_INTEREST_FAILED, // 53 REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, //54 REPAY_BORROW_COMPTROLLER_REJECTION, // 55 REPAY_BORROW_FRESHNESS_CHECK, // 56 REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, //57 REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 58 REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, // 59 SET_COLLATERAL_FACTOR_OWNER_CHECK, // 60 SET_COLLATERAL_FACTOR_VALIDATION, // 61 SET_COMPTROLLER_OWNER_CHECK, // 62 SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, //63 SET_INTEREST_RATE_MODEL_FRESH_CHECK, // 64 SET_INTEREST_RATE_MODEL_OWNER_CHECK, // 65 SET_MAX_ASSETS_OWNER_CHECK, // 66 SET_ORACLE_MARKET_NOT_LISTED, // 67 SET_PENDING_ADMIN_OWNER_CHECK, // 68 SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, // 69 SET_RESERVE_FACTOR_ADMIN_CHECK, // 70 SET_RESERVE_FACTOR_FRESH_CHECK, // 71 SET_RESERVE_FACTOR_BOUNDS_CHECK, // 72 TRANSFER_COMPTROLLER_REJECTION, // 73 TRANSFER_NOT_ALLOWED, // 74 TRANSFER_NOT_ENOUGH, // 75 TRANSFER_TOO_MUCH, // 76 ADD_RESERVES_ACCRUE_INTEREST_FAILED, // 77 ADD_RESERVES_FRESH_CHECK, // 78 ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE // 79 } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // File: contracts/CarefulMath.sol pragma solidity 0.5.17; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // File: contracts/Exponential.sol pragma solidity 0.5.17; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/EIP20Interface.sol pragma solidity 0.5.17; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // File: contracts/EIP20NonStandardInterface.sol pragma solidity 0.5.17; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // File: contracts/GToken.sol pragma solidity 0.5.17; /** * @title GToken Contract * @notice Abstract base for CTokens */ contract GToken is GTokenInterface, Exponential, TokenErrorReporter { bytes32 internal constant projectHash = keccak256(abi.encodePacked("ZILD")); /** * @notice Underlying asset for this GToken */ address public underlying; /** * @notice , ETH is native coin */ bool public underlyingIsNativeCoin; // borrow fee amount * borrowFee / 10000; uint public borrowFee; // redeem fee amount = redeem amount * redeemFee / 10000; uint public redeemFee; uint public constant TEN_THOUSAND = 10000; // max fee borrow redeem fee : 1% uint public constant MAX_BORROW_REDEEM_FEE = 100; // borrow fee and redeemFee will send to feeTo address payable public feeTo; event NewBorrowFee(uint oldBorrowFee, uint newBorrowFee); event NewRedeemFee(uint oldRedeemFee, uint newRedeemFee); event NewFeeTo(address oldFeeTo, address newFeeTo); /** * @notice Initialize the money market * @param underlying_ Underlying asset for this GToken, ZETH's underlying is address(0) * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token * @param borrowFee_ borrow fee * @param redeemFee_ redeem fee * @param feeTo_ fee address */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, uint borrowFee_, uint redeemFee_, address payable feeTo_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); _setBorrowFee(borrowFee_); _setRedeemFee(redeemFee_); _setFeeTo(feeTo_); name = name_; symbol = symbol_; decimals = decimals_; underlying = underlying_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice . * @dev Admin function: change borrowFee. * @param newBorrowFee newBorrowFee * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setBorrowFee(uint newBorrowFee) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } require(newBorrowFee <= MAX_BORROW_REDEEM_FEE, "newBorrowFee is greater than MAX_BORROW_REDEEM_FEE"); emit NewBorrowFee(borrowFee, newBorrowFee); borrowFee = newBorrowFee; return uint(Error.NO_ERROR); } /** * @notice . * @dev Admin function: change redeemFee. * @param newRedeemFee newRedeemFee * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRedeemFee(uint newRedeemFee) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } require(newRedeemFee <= MAX_BORROW_REDEEM_FEE, "newRedeemFee is greater than MAX_BORROW_REDEEM_FEE"); emit NewBorrowFee(redeemFee, newRedeemFee); redeemFee = newRedeemFee; return uint(Error.NO_ERROR); } /** * @notice . * @dev Admin function: change feeTo. * @param newFeeTo newFeeTo * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setFeeTo(address payable newFeeTo) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } require(newFeeTo != address(0), "newFeeTo is zero address"); emit NewFeeTo(feeTo, newFeeTo); feeTo = newFeeTo; return uint(Error.NO_ERROR); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this gToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this gToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the GToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the GToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this gToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The gToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the gToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The gToken must handle variations between ERC-20 and ETH underlying. * On success, the gToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ uint fee = 0; uint redeemAmountMinusFee = 0; (vars.mathErr, fee) = mulUInt(vars.redeemAmount, redeemFee); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, redeemAmountMinusFee) = subUInt(vars.redeemAmount, fee); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } // doTransferOut(redeemer, vars.redeemAmount); // vars.redeemAmount = redeemAmountMinusFee + fee doTransferOut(redeemer, redeemAmountMinusFee); doTransferOut(feeTo, fee); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The gToken must handle variations between ERC-20 and ETH underlying. * On success, the gToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ uint fee = 0; uint borrowAmountMinusFee = 0; (vars.mathErr, fee) = mulUInt(borrowAmount, borrowFee); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, borrowAmountMinusFee) = subUInt(borrowAmount, fee); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } doTransferOut(borrower, borrowAmountMinusFee); doTransferOut(feeTo, fee); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The gToken must handle variations between ERC-20 and ETH underlying. * On success, the gToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this gToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this gToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another gToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed gToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another GToken. * Its absolutely critical to use msg.sender as the seizer gToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed gToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The gToken must handle variations between ERC-20 and ETH underlying. * On success, the gToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // File: contracts/PriceOracle.sol pragma solidity 0.5.17; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a gToken asset * @param gToken The gToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(GToken gToken) external view returns (uint); /** * Get underlying market price for web app */ function getMarketPrice(string calldata symbol) external view returns (uint); /** * Get underlying oracle price for web app */ function price(string calldata symbol) external view returns (uint); } // File: contracts/ComptrollerStorage.sol pragma solidity 0.5.17; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Supervisor */ address public comptrollerImplementation; /** * @notice Pending brains of Supervisor */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => GToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { /// @notice A list of all markets GToken[] public allMarkets; } // File: contracts/Comptroller.sol pragma solidity 0.5.17; /** * @title Comptroller Contract */ contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(GToken gToken); /// @notice Emitted when an account enters a market event MarketEntered(GToken gToken, address account); /// @notice Emitted when an account exits a market event MarketExited(GToken gToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(GToken gToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionGlobalPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionMarketPaused(GToken gToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(GToken gToken, bool isComped); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (GToken[] memory) { GToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param gToken The gToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, GToken gToken) external view returns (bool) { return markets[address(gToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param gTokens The list of addresses of the gToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory gTokens) public returns (uint[] memory) { uint len = gTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { GToken gToken = GToken(gTokens[i]); results[i] = uint(addToMarketInternal(gToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param gToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(GToken gToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(gToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(gToken); emit MarketEntered(gToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param gTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address gTokenAddress) external returns (uint) { GToken gToken = GToken(gTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the gToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = gToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(gTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(gToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set gToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete gToken from the account’s list of assets */ // load into memory for faster iteration GToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == gToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 GToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(gToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param gToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address gToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[gToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[gToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param gToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address gToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused gToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param gToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of gTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address gToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(gToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } return uint(Error.NO_ERROR); } function redeemAllowedInternal(address gToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[gToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[gToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, GToken(gToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param gToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address gToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused gToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param gToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address gToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[gToken], "borrow is paused"); if (!markets[gToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[gToken].accountMembership[borrower]) { // only gTokens may call borrowAllowed if borrower not in market require(msg.sender == gToken, "sender must be gToken"); // attempt to add borrower to the market Error err = addToMarketInternal(GToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[gToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(GToken(gToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, GToken(gToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param gToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address gToken, address borrower, uint borrowAmount) external { // Shh - currently unused gToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param gToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address gToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[gToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param gToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address gToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused gToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param gTokenBorrowed Asset which was borrowed by the borrower * @param gTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address gTokenBorrowed, address gTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[gTokenBorrowed].isListed || !markets[gTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = GToken(gTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param gTokenBorrowed Asset which was borrowed by the borrower * @param gTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address gTokenBorrowed, address gTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused gTokenBorrowed; gTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param gTokenCollateral Asset which was used as collateral and will be seized * @param gTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address gTokenCollateral, address gTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[gTokenCollateral].isListed || !markets[gTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (GToken(gTokenCollateral).comptroller() != GToken(gTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param gTokenCollateral Asset which was used as collateral and will be seized * @param gTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address gTokenCollateral, address gTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused gTokenCollateral; gTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param gToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of gTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address gToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(gToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param gToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of gTokens to transfer */ function transferVerify(address gToken, address src, address dst, uint transferTokens) external { // Shh - currently unused gToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `gTokenBalance` is the number of gTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint gTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param gTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address gTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(gTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param gTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral gToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, GToken gTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in GToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { GToken asset = assets[i]; // Read the balances and exchange rate from the gToken (oErr, vars.gTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * gTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.gTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with gTokenModify if (asset == gTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in gToken.liquidateBorrowFresh) * @param gTokenBorrowed The address of the borrowed gToken * @param gTokenCollateral The address of the collateral gToken * @param actualRepayAmount The amount of gTokenBorrowed underlying to convert into gTokenCollateral tokens * @return (errorCode, number of gTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address gTokenBorrowed, address gTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(GToken(gTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(GToken(gTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = GToken(gTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param gToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(GToken gToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(gToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(gToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(gToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param gToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(GToken gToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(gToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } gToken.isCToken(); // Sanity check to make sure its really a GToken markets[address(gToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0}); _addMarketInternal(address(gToken)); emit MarketListed(gToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address gToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != GToken(gToken), "market already added"); } allMarkets.push(GToken(gToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(GToken gToken, bool state) public returns (bool) { require(markets[address(gToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(gToken)] = state; emit ActionMarketPaused(gToken, "Mint", state); return state; } function _setBorrowPaused(GToken gToken, bool state) public returns (bool) { require(markets[address(gToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(gToken)] = state; emit ActionMarketPaused(gToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionGlobalPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionGlobalPaused("Seize", state); return state; } /* function _become(Supervisor unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } */ /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (GToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } }
* @notice . @dev Admin function: change borrowFee. @param newBorrowFee newBorrowFee @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller = admin
function _setBorrowFee(uint newBorrowFee) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } require(newBorrowFee <= MAX_BORROW_REDEEM_FEE, "newBorrowFee is greater than MAX_BORROW_REDEEM_FEE"); emit NewBorrowFee(borrowFee, newBorrowFee); borrowFee = newBorrowFee; return uint(Error.NO_ERROR); }
598,267
[ 1, 18, 225, 7807, 445, 30, 2549, 225, 29759, 14667, 18, 225, 394, 38, 15318, 14667, 225, 394, 38, 15318, 14667, 327, 2254, 374, 33, 4768, 16, 3541, 279, 5166, 261, 5946, 1068, 13289, 18, 18281, 364, 3189, 13176, 2073, 4894, 273, 3981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 38, 15318, 14667, 12, 11890, 394, 38, 15318, 14667, 13, 1071, 1135, 261, 11890, 13, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 3981, 13, 288, 203, 5411, 327, 2321, 12, 668, 18, 2124, 28383, 16, 13436, 966, 18, 4043, 67, 25691, 67, 15468, 67, 29602, 67, 10687, 1769, 203, 3639, 289, 203, 203, 3639, 2583, 12, 2704, 38, 15318, 14667, 1648, 4552, 67, 38, 916, 11226, 67, 862, 1639, 3375, 67, 8090, 41, 16, 315, 2704, 38, 15318, 14667, 353, 6802, 2353, 4552, 67, 38, 916, 11226, 67, 862, 1639, 3375, 67, 8090, 41, 8863, 203, 203, 3639, 3626, 1166, 38, 15318, 14667, 12, 70, 15318, 14667, 16, 394, 38, 15318, 14667, 1769, 203, 203, 3639, 29759, 14667, 273, 394, 38, 15318, 14667, 31, 203, 203, 3639, 327, 2254, 12, 668, 18, 3417, 67, 3589, 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 ]
./partial_match/137/0x4571C2452fFb3f8107bFE023864d61d96c78d8A3/sources/GeniosClucDai.sol
IPool(PoolAddr).AddUser(level, userAddr); emit RankEarners(Users[userAddr].Id, userAddr, level);
function _activeUserRank(address userAddr, uint8 level) private { if ( level != LAST_LEVEL && Users[userAddr].Ref != Id0 && !Users[Users[userAddr].Ref].Ranks[level + 1].IsActive ) Users[Users[userAddr].Ref].Ranks[level + 1].DirectRefs++; Users[userAddr].Ranks[level].IsActive = true; }
3,515,075
[ 1, 2579, 1371, 12, 2864, 3178, 2934, 986, 1299, 12, 2815, 16, 729, 3178, 1769, 3626, 534, 2304, 41, 1303, 414, 12, 6588, 63, 1355, 3178, 8009, 548, 16, 729, 3178, 16, 1801, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 389, 3535, 1299, 12925, 12, 2867, 729, 3178, 16, 2254, 28, 1801, 13, 3238, 288, 203, 565, 309, 261, 203, 1377, 1801, 480, 15612, 67, 10398, 597, 203, 1377, 12109, 63, 1355, 3178, 8009, 1957, 480, 3124, 20, 597, 203, 1377, 401, 6588, 63, 6588, 63, 1355, 3178, 8009, 1957, 8009, 12925, 87, 63, 2815, 397, 404, 8009, 2520, 3896, 203, 565, 262, 12109, 63, 6588, 63, 1355, 3178, 8009, 1957, 8009, 12925, 87, 63, 2815, 397, 404, 8009, 5368, 9837, 9904, 31, 203, 203, 565, 12109, 63, 1355, 3178, 8009, 12925, 87, 63, 2815, 8009, 2520, 3896, 273, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../contracts/ActiveBridgeSetBlockRelay.sol"; /** * @title Test Helper for the new block Relay contract * @dev The aim of this contract is to raise the visibility modifier of new block relay contract functions for testing purposes * @author Witnet Foundation */ contract ABSBlockRelayTestHelper is ActiveBridgeSetBlockRelay { ActiveBridgeSetBlockRelay public br; uint256 public timestamp; constructor ( uint256 _witnetGenesis, uint256 _epochSeconds, uint256 _firstBlock, address _wbiAddress) public ActiveBridgeSetBlockRelay(_witnetGenesis, _epochSeconds, _firstBlock, _wbiAddress) {} // Sets the current epoch to be the next function nextEpoch() external { currentEpoch = currentEpoch + 1; } // Sets the currentEpoch function setEpoch(uint256 _epoch) external { currentEpoch = _epoch; } // Gets the vote with the poposeBlock inputs function getVote( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote) external pure returns(uint256) { uint256 vote = uint256( sha256( abi.encodePacked( _blockHash, _epoch, _drMerkleRoot, _tallyMerkleRoot, _previousVote))); return vote; } // Gets the blockHash of a vote finalized in a specific epoch function getBlockHash(uint256 _epoch) external view returns (uint256) { uint256 blockHash = epochFinalizedBlock[_epoch]; return blockHash; } // Gets the length of the candidates array function getCandidatesLength() external view returns (uint256) { return candidates.length; } // Checks if the epoch is finalized function checkEpochFinalized(uint256 _epoch) external view returns (bool) { if (epochFinalizedBlock[_epoch] != 0) { return true; } } // Updates the currentEpoch function updateEpoch() public view override returns (uint256) { return currentEpoch; } }
Updates the currentEpoch
function updateEpoch() public view override returns (uint256) { return currentEpoch; }
5,430,843
[ 1, 5121, 326, 783, 14638, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 14638, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 783, 14638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1826b0871096b3558E8ed1802629a0232288F8e8/sources/UniftyFarm.sol
1 point per day per staked token, multiples of this lowers time per staked token
uint256 public rewardRate = 86400;
2,776,806
[ 1, 21, 1634, 1534, 2548, 1534, 384, 9477, 1147, 16, 3309, 6089, 434, 333, 4587, 414, 813, 1534, 384, 9477, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 202, 11890, 5034, 1071, 19890, 4727, 273, 21451, 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 ]
/* Copyright 2018 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/LICENSE2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; import "@0x/contracts-exchange-libs/contracts/src/LibExchangeSelectors.sol"; import "@0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol"; import "./MixinExchangeCalldata.sol"; import "./interfaces/IBalanceThresholdFilterCore.sol"; contract MixinBalanceThresholdFilterCore is IBalanceThresholdFilterCore, MixinExchangeCalldata, LibExchangeSelectors { /// @dev Executes an Exchange transaction iff the maker and taker meet /// the hold at least `BALANCE_THRESHOLD` of the asset `THRESHOLD_ASSET` OR /// the exchange function is a cancellation. /// Supported Exchange functions: /// batchFillOrders /// batchFillOrdersNoThrow /// batchFillOrKillOrders /// fillOrder /// fillOrderNoThrow /// fillOrKillOrder /// marketBuyOrders /// marketBuyOrdersNoThrow /// marketSellOrders /// marketSellOrdersNoThrow /// matchOrders /// cancelOrder /// batchCancelOrders /// cancelOrdersUpTo /// Trying to call any other exchange function will throw. /// @param salt Arbitrary number to ensure uniqueness of transaction hash. /// @param signerAddress Address of transaction signer. /// @param signedExchangeTransaction AbiV2 encoded calldata. /// @param signature Proof of signer transaction by signer. function executeTransaction( uint256 salt, address signerAddress, bytes calldata signedExchangeTransaction, bytes calldata signature ) external { // Get accounts whose balances must be validated address[] memory addressesToValidate = _getAddressesToValidate(signerAddress); // Validate account balances uint256 balanceThreshold = BALANCE_THRESHOLD; IThresholdAsset thresholdAsset = THRESHOLD_ASSET; for (uint256 i = 0; i < addressesToValidate.length; ++i) { uint256 addressBalance = thresholdAsset.balanceOf(addressesToValidate[i]); require( addressBalance >= balanceThreshold, "AT_LEAST_ONE_ADDRESS_DOES_NOT_MEET_BALANCE_THRESHOLD" ); } emit ValidatedAddresses(addressesToValidate); LibZeroExTransaction.ZeroExTransaction memory transaction = LibZeroExTransaction.ZeroExTransaction({ salt: salt, data: signedExchangeTransaction, signerAddress: signerAddress }); // All addresses are valid. Execute exchange function. EXCHANGE.executeTransaction(transaction, signature); } /// @dev Constructs an array of addresses to be validated. /// Addresses depend on which Exchange function is to be called /// (defined by `signedExchangeTransaction` above). /// @param signerAddress Address of transaction signer. /// @return addressesToValidate Array of addresses to validate. function _getAddressesToValidate(address signerAddress) internal pure returns (address[] memory addressesToValidate) { bytes4 exchangeFunctionSelector = bytes4(_exchangeCalldataload(0)); // solhint-disable expression-indent if ( exchangeFunctionSelector == BATCH_FILL_ORDERS_SELECTOR || exchangeFunctionSelector == BATCH_FILL_ORDERS_NO_THROW_SELECTOR || exchangeFunctionSelector == BATCH_FILL_OR_KILL_ORDERS_SELECTOR || exchangeFunctionSelector == MARKET_BUY_ORDERS_SELECTOR || exchangeFunctionSelector == MARKET_BUY_ORDERS_NO_THROW_SELECTOR || exchangeFunctionSelector == MARKET_SELL_ORDERS_SELECTOR || exchangeFunctionSelector == MARKET_SELL_ORDERS_NO_THROW_SELECTOR ) { addressesToValidate = _loadMakerAddressesFromOrderArray(0); addressesToValidate = addressesToValidate.append(signerAddress); } else if ( exchangeFunctionSelector == FILL_ORDER_SELECTOR || exchangeFunctionSelector == FILL_ORDER_NO_THROW_SELECTOR || exchangeFunctionSelector == FILL_OR_KILL_ORDER_SELECTOR ) { address makerAddress = _loadMakerAddressFromOrder(0); addressesToValidate = addressesToValidate.append(makerAddress); addressesToValidate = addressesToValidate.append(signerAddress); } else if (exchangeFunctionSelector == MATCH_ORDERS_SELECTOR) { address leftMakerAddress = _loadMakerAddressFromOrder(0); addressesToValidate = addressesToValidate.append(leftMakerAddress); address rightMakerAddress = _loadMakerAddressFromOrder(1); addressesToValidate = addressesToValidate.append(rightMakerAddress); addressesToValidate = addressesToValidate.append(signerAddress); } else if ( exchangeFunctionSelector != CANCEL_ORDER_SELECTOR && exchangeFunctionSelector != BATCH_CANCEL_ORDERS_SELECTOR && exchangeFunctionSelector != CANCEL_ORDERS_UP_TO_SELECTOR ) { revert("INVALID_OR_BLOCKED_EXCHANGE_SELECTOR"); } // solhint-enable expression-indent return addressesToValidate; } }
@dev Constructs an array of addresses to be validated. Addresses depend on which Exchange function is to be called (defined by `signedExchangeTransaction` above). @param signerAddress Address of transaction signer. @return addressesToValidate Array of addresses to validate. solhint-disable expression-indent
function _getAddressesToValidate(address signerAddress) internal pure returns (address[] memory addressesToValidate) { bytes4 exchangeFunctionSelector = bytes4(_exchangeCalldataload(0)); if ( exchangeFunctionSelector == BATCH_FILL_ORDERS_SELECTOR || exchangeFunctionSelector == BATCH_FILL_ORDERS_NO_THROW_SELECTOR || exchangeFunctionSelector == BATCH_FILL_OR_KILL_ORDERS_SELECTOR || exchangeFunctionSelector == MARKET_BUY_ORDERS_SELECTOR || exchangeFunctionSelector == MARKET_BUY_ORDERS_NO_THROW_SELECTOR || exchangeFunctionSelector == MARKET_SELL_ORDERS_SELECTOR || exchangeFunctionSelector == MARKET_SELL_ORDERS_NO_THROW_SELECTOR ) { addressesToValidate = _loadMakerAddressesFromOrderArray(0); addressesToValidate = addressesToValidate.append(signerAddress); } else if ( exchangeFunctionSelector == FILL_ORDER_SELECTOR || exchangeFunctionSelector == FILL_ORDER_NO_THROW_SELECTOR || exchangeFunctionSelector == FILL_OR_KILL_ORDER_SELECTOR ) { address makerAddress = _loadMakerAddressFromOrder(0); addressesToValidate = addressesToValidate.append(makerAddress); addressesToValidate = addressesToValidate.append(signerAddress); address leftMakerAddress = _loadMakerAddressFromOrder(0); addressesToValidate = addressesToValidate.append(leftMakerAddress); address rightMakerAddress = _loadMakerAddressFromOrder(1); addressesToValidate = addressesToValidate.append(rightMakerAddress); addressesToValidate = addressesToValidate.append(signerAddress); } else if ( exchangeFunctionSelector != CANCEL_ORDER_SELECTOR && exchangeFunctionSelector != BATCH_CANCEL_ORDERS_SELECTOR && exchangeFunctionSelector != CANCEL_ORDERS_UP_TO_SELECTOR ) { revert("INVALID_OR_BLOCKED_EXCHANGE_SELECTOR"); } }
12,617,905
[ 1, 13262, 392, 526, 434, 6138, 358, 506, 10266, 18, 1377, 23443, 2447, 603, 1492, 18903, 445, 353, 358, 506, 2566, 1377, 261, 2178, 635, 1375, 5679, 11688, 3342, 68, 5721, 2934, 225, 10363, 1887, 5267, 434, 2492, 10363, 18, 327, 6138, 774, 4270, 1510, 434, 6138, 358, 1954, 18, 3704, 11317, 17, 8394, 2652, 17, 9355, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 7148, 774, 4270, 12, 2867, 10363, 1887, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 2867, 8526, 3778, 6138, 774, 4270, 13, 203, 565, 288, 203, 3639, 1731, 24, 7829, 2083, 4320, 273, 1731, 24, 24899, 16641, 1477, 72, 3145, 6189, 12, 20, 10019, 203, 3639, 309, 261, 203, 5411, 7829, 2083, 4320, 422, 605, 5858, 67, 29818, 67, 7954, 55, 67, 4803, 916, 2868, 747, 203, 5411, 7829, 2083, 4320, 422, 605, 5858, 67, 29818, 67, 7954, 55, 67, 3417, 67, 2455, 11226, 67, 4803, 916, 377, 747, 203, 5411, 7829, 2083, 4320, 422, 605, 5858, 67, 29818, 67, 916, 67, 47, 15125, 67, 7954, 55, 67, 4803, 916, 1377, 747, 203, 5411, 7829, 2083, 4320, 422, 20503, 1584, 67, 3000, 61, 67, 7954, 55, 67, 4803, 916, 2868, 747, 203, 5411, 7829, 2083, 4320, 422, 20503, 1584, 67, 3000, 61, 67, 7954, 55, 67, 3417, 67, 2455, 11226, 67, 4803, 916, 377, 747, 203, 5411, 7829, 2083, 4320, 422, 20503, 1584, 67, 1090, 4503, 67, 7954, 55, 67, 4803, 916, 2398, 747, 203, 5411, 7829, 2083, 4320, 422, 20503, 1584, 67, 1090, 4503, 67, 7954, 55, 67, 3417, 67, 2455, 11226, 67, 4803, 916, 203, 3639, 262, 288, 203, 5411, 6138, 774, 4270, 273, 389, 945, 12373, 7148, 1265, 2448, 1076, 12, 20, 1769, 203, 5411, 6138, 774, 4270, 273, 6138, 774, 4270, 18, 6923, 12, 2977, 264, 1887, 1769, 203, 3639, 289, 469, 309, 261, 203, 5411, 7829, 2083, 4320, 422, 8445, 48, 67, 2 ]
// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.13; import "./utils/BaseTest.sol"; import "src/Contract.sol"; contract TestContract is BaseTest { Contract private c; constructor() { // Created (during `setUp()`) users will be available in `users` state variable // Setup test to create 2 test user with 100 ether in balance each // preSetUp(2); // Setup test to create 2 test user with 1 ether in balance each // preSetUp(2, 1 ether); // Setup test to create 2 test user with 1 ether in balance each and label them accordingly string[] memory userLabels = new string[](2); userLabels[0] = "Alice"; userLabels[1] = "Bob"; preSetUp(2, 100 ether, userLabels); } function setUp() public override { // Call the BaseTest setUp() function that will also create testsing accounts super.setUp(); c = new Contract(); } function testSetUp() public { assertEq(users.length, 2); assertEq(users[0].balance, 100 ether); } function testBar() public { assertEq(uint256(1), uint256(1), "ok"); } function testFoo(uint256 x) public { vm.assume(x < type(uint128).max); assertEq(x + x, x * 2); } }
Created (during `setUp()`) users will be available in `users` state variable Setup test to create 2 test user with 100 ether in balance each preSetUp(2); Setup test to create 2 test user with 1 ether in balance each preSetUp(2, 1 ether); Setup test to create 2 test user with 1 ether in balance each and label them accordingly
constructor() { string[] memory userLabels = new string[](2); userLabels[0] = "Alice"; userLabels[1] = "Bob"; preSetUp(2, 100 ether, userLabels); }
5,404,758
[ 1, 6119, 261, 72, 4017, 1375, 542, 1211, 20338, 13, 3677, 903, 506, 2319, 316, 1375, 5577, 68, 919, 2190, 10939, 1842, 358, 752, 576, 1842, 729, 598, 2130, 225, 2437, 316, 11013, 1517, 675, 694, 1211, 12, 22, 1769, 10939, 1842, 358, 752, 576, 1842, 729, 598, 404, 225, 2437, 316, 11013, 1517, 675, 694, 1211, 12, 22, 16, 404, 225, 2437, 1769, 10939, 1842, 358, 752, 576, 1842, 729, 598, 404, 225, 2437, 316, 11013, 1517, 471, 1433, 2182, 15905, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 3885, 1435, 288, 203, 203, 203, 203, 3639, 533, 8526, 3778, 729, 5888, 273, 394, 533, 8526, 12, 22, 1769, 203, 3639, 729, 5888, 63, 20, 65, 273, 315, 37, 2008, 14432, 203, 3639, 729, 5888, 63, 21, 65, 273, 315, 38, 947, 14432, 203, 3639, 675, 694, 1211, 12, 22, 16, 2130, 225, 2437, 16, 729, 5888, 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 ]
pragma solidity ^0.4.25; /* * ---How to use: * 1. Send from ETH wallet to the smart contract address any amount ETH. * 2a. Claim your profit by sending 0 ether transaction (1 time per 12 hour) * OR * 2b. Send more ether to reinvest AND get your profit * 2c. If you hold, the percentage grows * 3. If you earn more than 150%, you can withdraw only one finish time * 4. If you want withdraw invested, send 0.00000911 ether * * RECOMMENDED GAS LIMIT: 150000 * RECOMMENDED GAS PRICE: https://ethgasstation.info/ * * THE PROJECT HAS HIGH RISKS! * PROJECT MAKE PAYMENTS IF BALANCE HAS ETHER! */ contract HodlETH { // records amounts invested mapping (address => uint) public userInvested; // records blocks at which investments were made mapping (address => uint) public entryTime; // records how much you withdraw mapping (address => uint) public withdrawnAmount; //records you use the referral program or not mapping (address => uint) public referrerOn; // marketing fund 6% address public advertisingFund = 0x01429d58058B3e84F6f264D91254EA3a96E1d2B7; uint public advertisingPercent = 6; // tech support fund 2 % address techSupportFund = 0x0D5dB78b35ecbdD22ffeA91B46a6EC77dC09EA4a; uint public techSupportPercent = 2; // "hodl" mode uint public startPercent = 25; // 2.5% uint public fiveDayHodlPercent = 30; // 3% uint public tenDayHodlPercent = 35; // 3.5% uint public twentyDayHodlPercent = 45; // 4.5% // bonus percent of balance uint public lowBalance = 500 ether; uint public middleBalance = 2000 ether; uint public highBalance = 3500 ether; uint public soLowBalanceBonus = 5; // 0.5% uint public lowBalanceBonus = 10; // 1% uint public middleBalanceBonus = 15; // 1.5% uint public highBalanceBonus = 20; // 2% // get bonus percent function bonusPercent() public view returns(uint){ uint balance = address(this).balance; if (balance < lowBalance){ return (soLowBalanceBonus); // if balance < 500 ether return 0.5% } if (balance > lowBalance && balance < middleBalance){ return (lowBalanceBonus); // if balance > 500 ether and balance < 2000 ether return 1% } if (balance > middleBalance && balance < highBalance){ return (middleBalanceBonus); // if balance > 2000 ether and balance < 3500 ether return 1.5% } if (balance > highBalance){ return (highBalanceBonus); // if balance > 3500 ether return 2% } } // get personal percent function personalPercent() public view returns(uint){ uint hodl = block.number - entryTime[msg.sender]; // how many blocks you hold, 1 day = 6100 blocks if (hodl < 30500){ return (startPercent); // if hodl < 5 day, return 2.5% } if (hodl > 30500 && hodl < 61000){ return (fiveDayHodlPercent); // if hodl > 5 day and hodl < 10 day, return 3% } if (hodl > 61000 && hodl < 122000){ return (tenDayHodlPercent); // if hodl > 10 day and hodl < 20 day, return 3.5% } if (hodl > 122000){ return (twentyDayHodlPercent); // if hodl > 20 day, return 3.5% } } // if send 0.00000911 ETH contract will return your invest, else make invest function() external payable { if (msg.value == 0.00000911 ether) { returnInvestment(); } else { invest(); } } // return of deposit(userInvested - withdrawnAmount - (userInvested / 10(fund fee)) , after delete user record function returnInvestment() timeWithdrawn private{ if(userInvested[msg.sender] > 0){ uint refundAmount = userInvested[msg.sender] - withdrawnAmount[msg.sender] - (userInvested[msg.sender] / 10); require(userInvested[msg.sender] > refundAmount, 'You have already returned the investment'); userInvested[msg.sender] = 0; entryTime[msg.sender] = 0; withdrawnAmount[msg.sender] = 0; msg.sender.transfer(refundAmount); } } // make a contribution function invest() timeWithdrawn maxInvested private { if (msg.value > 0 ){ // call terminal terminal(); // record invested amount (msg.value) of this transaction userInvested[msg.sender] += msg.value; // sending fee for advertising and tech support advertisingFund.transfer(msg.value * advertisingPercent / 100); techSupportFund.transfer(msg.value * techSupportPercent / 100); // if you entered the address that invited you and didn’t do this before if (msg.data.length != 0 && referrerOn[msg.sender] != 1){ //pays his bonus transferRefBonus(); } } else{ // call terminal terminal(); } } function terminal() internal { // if the user received 150% or more of his contribution, delete the user if (userInvested[msg.sender] * 15 / 10 < withdrawnAmount[msg.sender]){ userInvested[msg.sender] = 0; entryTime[msg.sender] = 0; withdrawnAmount[msg.sender] = 0; referrerOn[msg.sender] = 0; } else { // you percent = bonusPercent + personalPercent, min 3% and max 6.5% uint percent = bonusPercent() + personalPercent(); // calculate profit amount as such: // amount = (amount invested) * you percent * (blocks since last transaction) / 6100 // 6100 is an average block count per day produced by Ethereum blockchain uint amount = userInvested[msg.sender] * percent / 1000 * ((block.number - entryTime[msg.sender]) / 6100); // record block number entryTime[msg.sender] = block.number; // record withdraw amount withdrawnAmount[msg.sender] += amount; // send calculated amount of ether directly to sender (aka YOU) msg.sender.transfer(amount); } } // convert bytes to eth address function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } // transfer referrer bonus of invested function transferRefBonus() private { address referrer = bytesToAddress(msg.data); if (referrer != msg.sender && userInvested[referrer] != 0){ referrerOn[msg.sender] = 1; uint refBonus = msg.value * 20 / 1000; referrer.transfer(refBonus); } } modifier timeWithdrawn(){ require(entryTime[msg.sender] + 3050 < block.number, 'Withdraw and deposit no more 1 time per 12 hour'); _; } modifier maxInvested(){ require(msg.value <= 25 ether, 'Max invested 25 ETH per 12 hours'); _; } }
if hodl > 20 day, return 3.5%
return (twentyDayHodlPercent);
7,237,211
[ 1, 430, 366, 369, 80, 405, 4200, 2548, 16, 327, 890, 18, 25, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 327, 261, 11246, 319, 93, 4245, 44, 369, 80, 8410, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "../libs/BaseRelayRecipient.sol"; import "hardhat/console.sol"; interface IRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts); } interface ICurve { function exchange(int128 i, int128 j, uint dx, uint min_dy) external; } interface IChainlink { function latestAnswer() external view returns (int256); } interface IStrategy { function invest(uint amount) external; function withdraw(uint sharePerc, uint[] calldata tokenPrice) external; function switchMode(uint[] calldata tokenPrice) external; function collectProfitAndUpdateWatermark() external returns (uint); function adjustWatermark(uint amount, bool signs) external; function reimburse(uint sharePerc) external returns (uint); function emergencyWithdraw() external; function profitFeePerc() external view returns (uint); function setProfitFeePerc(uint profitFeePerc) external; function watermark() external view returns (uint); function getAllPoolInETH() external view returns (uint); } contract TAVault is Initializable, ERC20Upgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, BaseRelayRecipient { using SafeERC20Upgradeable for IERC20Upgradeable; IERC20Upgradeable constant USDT = IERC20Upgradeable(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20Upgradeable constant USDC = IERC20Upgradeable(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20Upgradeable constant DAI = IERC20Upgradeable(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20Upgradeable constant WETH = IERC20Upgradeable(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IRouter constant sushiRouter = IRouter(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); ICurve constant curve = ICurve(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); // 3pool IStrategy public strategy; uint[] public percKeepInVault; uint public fees; uint[] public networkFeeTier2; uint public customNetworkFeeTier; uint[] public networkFeePerc; uint public customNetworkFeePerc; // Temporarily variable for LP token distribution only address[] addresses; mapping(address => uint) public depositAmt; // Amount in USD (18 decimals) uint totalDepositAmt; address public treasuryWallet; address public communityWallet; address public strategist; address public admin; event Deposit(address caller, uint amtDeposit, address tokenDeposit); event Withdraw(address caller, uint amtWithdraw, address tokenWithdraw, uint shareBurned); event Invest(uint amount); event DistributeLPToken(address receiver, uint shareMinted); event TransferredOutFees(uint fees, address token); event Reimburse(address token, uint amount); event Reinvest(uint amount); event SetNetworkFeeTier2(uint[] oldNetworkFeeTier2, uint[] newNetworkFeeTier2); event SetCustomNetworkFeeTier(uint oldCustomNetworkFeeTier, uint newCustomNetworkFeeTier); event SetNetworkFeePerc(uint[] oldNetworkFeePerc, uint[] newNetworkFeePerc); event SetCustomNetworkFeePerc(uint oldCustomNetworkFeePerc, uint newCustomNetworkFeePerc); event SetProfitFeePerc(uint oldProfitFeePerc, uint profitFeePerc); event SetPercKeepInVault(uint[] oldPercKeepInVault, uint[] newPercKeepInVault); event SetTreasuryWallet(address oldTreasuryWallet, address newTreasuryWallet); event SetCommunityWallet(address oldCommunityWallet, address newCommunityWallet); event SetStrategistWallet(address oldStrategistWallet, address newStrategistWallet); event SetAdminWallet(address oldAdmin, address newAdmin); event SetBiconomy(address oldBiconomy, address newBiconomy); modifier onlyOwnerOrAdmin { require(msg.sender == owner() || msg.sender == address(admin), "Only owner or admin"); _; } function initialize( string calldata name, string calldata ticker, address _treasuryWallet, address _communityWallet, address _strategist, address _admin, address _biconomy, address _strategy ) external initializer { __ERC20_init(name, ticker); __Ownable_init(); strategy = IStrategy(_strategy); treasuryWallet = _treasuryWallet; communityWallet = _communityWallet; strategist = _strategist; admin = _admin; trustedForwarder = _biconomy; networkFeeTier2 = [50000*1e18+1, 100000*1e18]; customNetworkFeeTier = 1000000*1e18; networkFeePerc = [100, 75, 50]; customNetworkFeePerc = 25; percKeepInVault = [300, 300, 300]; // USDT, USDC, DAI USDT.safeApprove(address(sushiRouter), type(uint).max); USDT.safeApprove(address(curve), type(uint).max); USDC.safeApprove(address(sushiRouter), type(uint).max); USDC.safeApprove(address(curve), type(uint).max); DAI.safeApprove(address(sushiRouter), type(uint).max); DAI.safeApprove(address(curve), type(uint).max); WETH.safeApprove(address(sushiRouter), type(uint).max); WETH.safeApprove(address(strategy), type(uint).max); } function deposit(uint amount, IERC20Upgradeable token) external nonReentrant whenNotPaused { require(msg.sender == tx.origin || isTrustedForwarder(msg.sender), "Only EOA or Biconomy"); require(amount > 0, "Amount must > 0"); require(token == USDT || token == USDC || token == DAI, "Invalid token deposit"); address msgSender = _msgSender(); token.safeTransferFrom(msgSender, address(this), amount); if (token != DAI) amount *= 1e12; uint amtDeposit = amount; uint _networkFeePerc; if (amount < networkFeeTier2[0]) _networkFeePerc = networkFeePerc[0]; // Tier 1 else if (amount <= networkFeeTier2[1]) _networkFeePerc = networkFeePerc[1]; // Tier 2 else if (amount < customNetworkFeeTier) _networkFeePerc = networkFeePerc[2]; // Tier 3 else _networkFeePerc = customNetworkFeePerc; // Custom Tier uint fee = amount * _networkFeePerc / 10000; fees += fee; amount -= fee; if (depositAmt[msgSender] == 0) { addresses.push(msgSender); depositAmt[msgSender] = amount; } else depositAmt[msgSender] += amount; totalDepositAmt += amount; emit Deposit(msgSender, amtDeposit, address(token)); } function withdraw(uint share, IERC20Upgradeable token, uint[] calldata tokenPrice) external nonReentrant { require(msg.sender == tx.origin, "Only EOA"); require(share > 0 || share <= balanceOf(msg.sender), "Invalid share amount"); require(token == USDT || token == USDC || token == DAI, "Invalid token withdraw"); uint _totalSupply = totalSupply(); uint withdrawAmt = (getAllPoolInUSD() - totalDepositAmt) * share / _totalSupply; _burn(msg.sender, share); uint tokenAmtInVault = token.balanceOf(address(this)); if (token != DAI) tokenAmtInVault *= 1e12; if (withdrawAmt < tokenAmtInVault) { // Enough token in vault to withdraw if (token != DAI) withdrawAmt /= 1e12; token.safeTransfer(msg.sender, withdrawAmt); } else { // Not enough token in vault to withdraw, try if enough if swap from other token in vault (address token1, uint token1AmtInVault, address token2, uint token2AmtInVault) = getOtherTokenAndBal(token); if (withdrawAmt < tokenAmtInVault + token1AmtInVault) { // Enough if swap from token1 in vault uint amtSwapFromToken1 = withdrawAmt - tokenAmtInVault; if (token1 != address(DAI)) amtSwapFromToken1 /= 1e12; curve.exchange(getCurveId(token1), getCurveId(address(token)), amtSwapFromToken1, amtSwapFromToken1 * 99 / 100); withdrawAmt = token.balanceOf(address(this)); token.safeTransfer(msg.sender, withdrawAmt); } else if (withdrawAmt < tokenAmtInVault + token1AmtInVault + token2AmtInVault) { // Not enough if swap from token1 in vault but enough if swap from token1 + token2 in vault uint amtSwapFromToken2 = withdrawAmt - tokenAmtInVault - token1AmtInVault; if (token1AmtInVault > 0) { if (token1 != address(DAI)) token1AmtInVault /= 1e12; curve.exchange(getCurveId(token1), getCurveId(address(token)), token1AmtInVault, token1AmtInVault * 99 / 100); } if (token2AmtInVault > 0) { uint minAmtOutToken2 = amtSwapFromToken2 * 99 / 100; if (token2 != address(DAI)) amtSwapFromToken2 /= 1e12; if (token != DAI) minAmtOutToken2 /= 1e12; curve.exchange(getCurveId(token2), getCurveId(address(token)), amtSwapFromToken2, minAmtOutToken2); } withdrawAmt = token.balanceOf(address(this)); token.safeTransfer(msg.sender, withdrawAmt); } else { // Not enough if swap from token1 + token2 in vault, need to withdraw from strategy if (!paused()) { withdrawAmt = withdrawFromStrategy(token, withdrawAmt, tokenAmtInVault, tokenPrice); } else { withdrawAmt = withdrawWhenPaused(token, share, _totalSupply, tokenPrice); } } } emit Withdraw(msg.sender, withdrawAmt, address(token), share); } function withdrawFromStrategy( IERC20Upgradeable token, uint withdrawAmt, uint tokenAmtInVault, uint[] calldata tokenPrice ) private returns (uint) { strategy.withdraw(withdrawAmt - tokenAmtInVault, tokenPrice); strategy.adjustWatermark(withdrawAmt - tokenAmtInVault, false); if (token != DAI) tokenAmtInVault /= 1e12; uint WETHAmt = WETH.balanceOf(address(this)); uint amountOutMin = WETHAmt * tokenPrice[0] / 1e18; withdrawAmt = (sushiRouter.swapExactTokensForTokens( WETHAmt, amountOutMin, getPath(address(WETH), address(token)), address(this), block.timestamp )[1]) + tokenAmtInVault; token.safeTransfer(msg.sender, withdrawAmt); return withdrawAmt; } function withdrawWhenPaused( IERC20Upgradeable token, uint share, uint _totalSupply, uint[] calldata tokenPrice ) private returns (uint withdrawAmt) { uint WETHAmt = WETH.balanceOf(address(this)); uint amountOutMin = WETHAmt * tokenPrice[0] / 1e18; withdrawAmt = (sushiRouter.swapExactTokensForTokens( WETHAmt * share / _totalSupply, amountOutMin, getPath(address(WETH), address(token)), msg.sender, block.timestamp ))[1]; } function invest() public whenNotPaused { require( msg.sender == admin || msg.sender == owner() || msg.sender == address(this), "Only authorized caller" ); if (strategy.watermark() > 0) collectProfitAndUpdateWatermark(); (uint USDTAmt, uint USDCAmt, uint DAIAmt) = transferOutFees(); (uint WETHAmt, uint tokenAmtToInvest, uint pool) = swapTokenToWETH(USDTAmt, USDCAmt, DAIAmt); if (tokenAmtToInvest > 0) { strategy.invest(WETHAmt); strategy.adjustWatermark(tokenAmtToInvest, true); } distributeLPToken(pool); emit Invest(WETHAmt); } function collectProfitAndUpdateWatermark() public whenNotPaused { require( msg.sender == address(this) || msg.sender == admin || msg.sender == owner(), "Only authorized caller" ); uint fee = strategy.collectProfitAndUpdateWatermark(); if (fee > 0) fees = fees + fee; } function distributeLPToken(uint pool) private { if (totalSupply() != 0) pool -= totalDepositAmt; address[] memory _addresses = addresses; for (uint i; i < _addresses.length; i ++) { address depositAcc = _addresses[i]; uint _depositAmt = depositAmt[depositAcc]; uint _totalSupply = totalSupply(); uint share = _totalSupply == 0 ? _depositAmt : _depositAmt * _totalSupply / pool; _mint(depositAcc, share); pool += _depositAmt; depositAmt[depositAcc] = 0; emit DistributeLPToken(depositAcc, share); } delete addresses; totalDepositAmt = 0; } function transferOutFees() public returns (uint USDTAmt, uint USDCAmt, uint DAIAmt) { require( msg.sender == address(this) || msg.sender == admin || msg.sender == owner(), "Only authorized caller" ); USDTAmt = USDT.balanceOf(address(this)); USDCAmt = USDC.balanceOf(address(this)); DAIAmt = DAI.balanceOf(address(this)); uint _fees = fees; if (_fees != 0) { IERC20Upgradeable token; if (USDTAmt * 1e12 > _fees) { token = USDT; _fees = _fees / 1e12; USDTAmt = USDTAmt - _fees; } else if (USDCAmt * 1e12 > _fees) { token = USDC; _fees = _fees / 1e12; USDCAmt = USDCAmt - _fees; } else if (DAIAmt > _fees) { token = DAI; DAIAmt = DAIAmt - _fees; } else return (USDTAmt, USDCAmt, DAIAmt); uint _fee = _fees * 2 / 5; // 40% token.safeTransfer(treasuryWallet, _fee); // 40% token.safeTransfer(communityWallet, _fee); // 40% token.safeTransfer(strategist, _fees - _fee - _fee); // 20% fees = 0; emit TransferredOutFees(_fees, address(token)); // Decimal follow _token } } function switchMode(uint[] calldata tokenPrice) external onlyOwnerOrAdmin whenNotPaused { strategy.switchMode(tokenPrice); } function swapTokenToWETH(uint USDTAmt, uint USDCAmt, uint DAIAmt) private returns (uint WETHAmt, uint tokenAmtToInvest, uint pool) { uint[] memory _percKeepInVault = percKeepInVault; pool = getAllPoolInUSD(); uint USDTAmtKeepInVault = calcTokenKeepInVault(_percKeepInVault[0], pool) / 1e12; if (USDTAmt > USDTAmtKeepInVault + 1e6) { USDTAmt -= USDTAmtKeepInVault; WETHAmt = sushiSwap(address(USDT), address(WETH), USDTAmt); tokenAmtToInvest = USDTAmt * 1e12; } uint USDCAmtKeepInVault = calcTokenKeepInVault(_percKeepInVault[1], pool) / 1e12; if (USDCAmt > USDCAmtKeepInVault + 1e6) { USDCAmt -= USDCAmtKeepInVault; WETHAmt += sushiSwap(address(USDC), address(WETH), USDCAmt); tokenAmtToInvest += USDCAmt * 1e12; } uint DAIAmtKeepInVault = calcTokenKeepInVault(_percKeepInVault[2], pool); if (DAIAmt > DAIAmtKeepInVault + 1e18) { DAIAmt -= DAIAmtKeepInVault; WETHAmt += sushiSwap(address(DAI), address(WETH), DAIAmt); tokenAmtToInvest += DAIAmt; } } function calcTokenKeepInVault(uint _percKeepInVault, uint pool) private pure returns (uint) { return pool * _percKeepInVault / 10000; } /// @param amount Amount to reimburse (decimal follow token) function reimburse(address token, uint amount) external onlyOwnerOrAdmin whenNotPaused { uint WETHAmt; WETHAmt = sushiRouter.getAmountsOut(amount, getPath(token, address(WETH)))[1]; WETHAmt = strategy.reimburse(WETHAmt); sushiSwap(address(WETH), token, WETHAmt); if (token != address(DAI)) amount *= 1e12; strategy.adjustWatermark(amount, false); emit Reimburse(token, amount); } function emergencyWithdraw() external onlyOwnerOrAdmin whenNotPaused { _pause(); strategy.emergencyWithdraw(); } function reinvest() external onlyOwnerOrAdmin whenPaused { _unpause(); uint WETHAmt = WETH.balanceOf(address(this)); strategy.invest(WETHAmt); uint ETHPriceInUSD = uint(IChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419).latestAnswer()); require(ETHPriceInUSD > 0, "ChainLink error"); strategy.adjustWatermark(WETHAmt * ETHPriceInUSD / 1e8, true); emit Reinvest(WETHAmt); } function sushiSwap(address from, address to, uint amount) private returns (uint) { return sushiRouter.swapExactTokensForTokens( amount, 0, getPath(from, to), address(this), block.timestamp )[1]; } function setNetworkFeeTier2(uint[] calldata _networkFeeTier2) external onlyOwner { require(_networkFeeTier2[0] != 0, "Minimun amount cannot be 0"); require(_networkFeeTier2[1] > _networkFeeTier2[0], "Maximun amount must > minimun amount"); /** * Network fee has three tier, but it is sufficient to have minimun and maximun amount of tier 2 * Tier 1: deposit amount < minimun amount of tier 2 * Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2 * Tier 3: amount > maximun amount of tier 2 */ uint[] memory oldNetworkFeeTier2 = networkFeeTier2; networkFeeTier2 = _networkFeeTier2; emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2); } function setCustomNetworkFeeTier(uint _customNetworkFeeTier) external onlyOwner { require(_customNetworkFeeTier > networkFeeTier2[1], "Must > tier 2"); uint oldCustomNetworkFeeTier = customNetworkFeeTier; customNetworkFeeTier = _customNetworkFeeTier; emit SetCustomNetworkFeeTier(oldCustomNetworkFeeTier, _customNetworkFeeTier); } function setNetworkFeePerc(uint[] calldata _networkFeePerc) external onlyOwner { require(_networkFeePerc[0] < 3001 && _networkFeePerc[1] < 3001 && _networkFeePerc[2] < 3001, "Not allow > 30%"); /** * _networkFeePerc contains an array of 3 elements, representing network fee of tier 1, tier 2 and tier 3 * For example networkFeePerc is [100, 75, 50], * which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5% (Denominator = 10000) */ uint[] memory oldNetworkFeePerc = networkFeePerc; networkFeePerc = _networkFeePerc; emit SetNetworkFeePerc(oldNetworkFeePerc, _networkFeePerc); } function setCustomNetworkFeePerc(uint _customNetworkFeePerc) external onlyOwner { require(_customNetworkFeePerc < networkFeePerc[2], "Not allow > tier 2"); uint oldCustomNetworkFeePerc = customNetworkFeePerc; customNetworkFeePerc = _customNetworkFeePerc; emit SetCustomNetworkFeePerc(oldCustomNetworkFeePerc, _customNetworkFeePerc); } function setProfitFeePerc(uint profitFeePerc) external onlyOwner { require(profitFeePerc < 3001, "Profit fee cannot > 30%"); uint oldProfitFeePerc = strategy.profitFeePerc(); strategy.setProfitFeePerc(profitFeePerc); emit SetProfitFeePerc(oldProfitFeePerc, profitFeePerc); } function setPercKeepInVault(uint[] calldata _percKeepInVault) external onlyOwner { uint[] memory oldPercKeepInVault = percKeepInVault; percKeepInVault = _percKeepInVault; emit SetPercKeepInVault(oldPercKeepInVault, _percKeepInVault); } function setTreasuryWallet(address _treasuryWallet) external onlyOwner { address oldTreasuryWallet = treasuryWallet; treasuryWallet = _treasuryWallet; emit SetTreasuryWallet(oldTreasuryWallet, _treasuryWallet); } function setCommunityWallet(address _communityWallet) external onlyOwner { address oldCommunityWallet = communityWallet; communityWallet = _communityWallet; emit SetCommunityWallet(oldCommunityWallet, _communityWallet); } function setStrategist(address _strategist) external { require(msg.sender == strategist || msg.sender == owner(), "Only owner or strategist"); address oldStrategist = strategist; strategist = _strategist; emit SetStrategistWallet(oldStrategist, _strategist); } function setAdmin(address _admin) external onlyOwner { address oldAdmin = admin; admin = _admin; emit SetAdminWallet(oldAdmin, _admin); } function setBiconomy(address _biconomy) external onlyOwner { address oldBiconomy = trustedForwarder; trustedForwarder = _biconomy; emit SetBiconomy(oldBiconomy, _biconomy); } function _msgSender() internal override(ContextUpgradeable, BaseRelayRecipient) view returns (address) { return BaseRelayRecipient._msgSender(); } function versionRecipient() external pure override returns (string memory) { return "1"; } function getOtherTokenAndBal(IERC20Upgradeable token) private view returns (address token1, uint token1AmtInVault, address token2, uint token2AmtInVault) { if (token == USDT) { token1 = address(USDC); token1AmtInVault = USDC.balanceOf(address(this)) * 1e12; token2 = address(DAI); token2AmtInVault = DAI.balanceOf(address(this)); } else if (token == USDC) { token1 = address(USDT); token1AmtInVault = USDT.balanceOf(address(this)) * 1e12; token2 = address(DAI); token2AmtInVault = DAI.balanceOf(address(this)); } else { token1 = address(USDT); token1AmtInVault = USDT.balanceOf(address(this)) * 1e12; token2 = address(USDC); token2AmtInVault = USDC.balanceOf(address(this)) * 1e12; } } function getCurveId(address token) private pure returns (int128) { if (token == address(USDT)) return 2; else if (token == address(USDC)) return 1; else return 0; // DAI } function getPath(address tokenA, address tokenB) private pure returns (address[] memory path) { path = new address[](2); path[0] = tokenA; path[1] = tokenB; } function getTotalPendingDeposits() external view returns (uint) { return addresses.length; } function getAllPoolInUSD() public view returns (uint) { // ETHPriceInUSD amount in 8 decimals uint ETHPriceInUSD = uint(IChainlink(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419).latestAnswer()); require(ETHPriceInUSD > 0, "ChainLink error"); uint tokenKeepInVault = USDT.balanceOf(address(this)) * 1e12 + USDC.balanceOf(address(this)) * 1e12 + DAI.balanceOf(address(this)); if (paused()) return WETH.balanceOf(address(this)) * ETHPriceInUSD / 1e8 + tokenKeepInVault - fees; uint strategyPoolInUSD = strategy.getAllPoolInETH() * ETHPriceInUSD / 1e8; return strategyPoolInUSD + tokenKeepInVault - fees; } /// @notice Can be use for calculate both user shares & APR function getPricePerFullShare() external view returns (uint) { return (getAllPoolInUSD() - totalDepositAmt) * 1e18 / totalSupply(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier:MIT pragma solidity 0.8.7; import "../interfaces/IRelayRecipient.sol"; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; /* * require a function to be called through GSN only */ modifier trustedForwarderOnly() { require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder"); _; } function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier:MIT pragma solidity 0.8.7; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address); function versionRecipient() external virtual view returns (string memory); }
* a contract must implement this interface in order to support relayed transaction. It is better to inherit the BaseRelayRecipient as its implementation./
abstract contract IRelayRecipient { function isTrustedForwarder(address forwarder) public virtual view returns(bool); function _msgSender() internal virtual view returns (address); function versionRecipient() external virtual view returns (string memory); pragma solidity 0.8.7; }
1,304,393
[ 1, 69, 6835, 1297, 2348, 333, 1560, 316, 1353, 358, 2865, 18874, 329, 2492, 18, 2597, 353, 7844, 358, 6811, 326, 3360, 27186, 18241, 487, 2097, 4471, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 467, 27186, 18241, 288, 203, 203, 565, 445, 353, 16950, 30839, 12, 2867, 364, 20099, 13, 1071, 5024, 1476, 1135, 12, 6430, 1769, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 5024, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 1177, 18241, 1435, 3903, 5024, 1476, 1135, 261, 1080, 3778, 1769, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 27, 31, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../interfaces/curve/IStableSwapPoolETH.sol"; import "../../interfaces/curve/IRegistry.sol"; import "../../interfaces/curve/IAddressProvider.sol"; import "../BaseController.sol"; contract CurveControllerETH is BaseController { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IAddressProvider public immutable addressProvider; uint256 public constant N_COINS = 2; address public constant ETH_REGISTRY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; constructor( address _manager, address _accessControl, address _addressRegistry, IAddressProvider _curveAddressProvider ) public BaseController(_manager, _accessControl, _addressRegistry) { require(address(_curveAddressProvider) != address(0), "INVALID_CURVE_ADDRESS_PROVIDER"); addressProvider = _curveAddressProvider; } /// @dev Necessary to withdraw ETH // solhint-disable-next-line no-empty-blocks receive() external payable {} /// @notice Deploy liquidity to Curve pool /// @dev Calls to external contract /// @dev We trust sender to send a true curve poolAddress. If it's not the case it will fail in the add_liquidity part. /// @param poolAddress Token addresses /// @param amounts List of amounts of coins to deposit /// @param minMintAmount Minimum amount of LP tokens to mint from the deposit function deploy( address poolAddress, uint256[N_COINS] calldata amounts, uint256 minMintAmount ) external payable onlyManager onlyAddLiquidity { address lpTokenAddress = _getLPToken(poolAddress); uint256 amountsLength = amounts.length; for (uint256 i = 0; i < amountsLength; i++) { if (amounts[i] > 0) { address coin = IStableSwapPoolETH(poolAddress).coins(i); require(addressRegistry.checkAddress(coin, 0), "INVALID_COIN"); uint256 balance = _getBalance(coin); require(balance >= amounts[i], "INSUFFICIENT_BALANCE"); if (coin != ETH_REGISTRY_ADDRESS) { _approve(IERC20(coin), poolAddress, amounts[i]); } } } uint256 lpTokenBalanceBefore = IERC20(lpTokenAddress).balanceOf(address(this)); IStableSwapPoolETH(poolAddress).add_liquidity{value: amounts[0]}(amounts, minMintAmount); uint256 lpTokenBalanceAfter = IERC20(lpTokenAddress).balanceOf(address(this)); require(lpTokenBalanceAfter.sub(lpTokenBalanceBefore) >= minMintAmount, "LP_AMT_TOO_LOW"); } /// @notice Withdraw liquidity from Curve pool /// @dev Calls to external contract /// @dev We trust sender to send a true curve poolAddress. If it's not the case it will fail in the remove_liquidity_imbalance part. /// @param poolAddress Token addresses /// @param amounts List of amounts of underlying coins to withdraw /// @param maxBurnAmount Maximum amount of LP token to burn in the withdrawal function withdrawImbalance( address poolAddress, uint256[N_COINS] memory amounts, uint256 maxBurnAmount ) external onlyManager onlyRemoveLiquidity { address lpTokenAddress = _getLPTokenAndApprove(poolAddress, maxBurnAmount); uint256 lpTokenBalanceBefore = IERC20(lpTokenAddress).balanceOf(address(this)); uint256[N_COINS] memory coinsBalancesBefore = _getCoinsBalances(poolAddress); IStableSwapPoolETH(poolAddress).remove_liquidity_imbalance(amounts, maxBurnAmount); uint256 lpTokenBalanceAfter = IERC20(lpTokenAddress).balanceOf(address(this)); uint256[N_COINS] memory coinsBalancesAfter = _getCoinsBalances(poolAddress); _compareCoinsBalances(coinsBalancesBefore, coinsBalancesAfter, amounts); require(lpTokenBalanceBefore.sub(lpTokenBalanceAfter) <= maxBurnAmount, "LP_COST_TOO_HIGH"); } /// @notice Withdraw liquidity from Curve pool /// @dev Calls to external contract /// @dev We trust sender to send a true curve poolAddress. If it's not the case it will fail in the remove_liquidity part. /// @param poolAddress Token addresses /// @param amount Quantity of LP tokens to burn in the withdrawal /// @param minAmounts Minimum amounts of underlying coins to receive function withdraw( address poolAddress, uint256 amount, uint256[N_COINS] memory minAmounts ) external onlyManager onlyRemoveLiquidity { address lpTokenAddress = _getLPTokenAndApprove(poolAddress, amount); uint256 lpTokenBalanceBefore = IERC20(lpTokenAddress).balanceOf(address(this)); uint256[N_COINS] memory coinsBalancesBefore = _getCoinsBalances(poolAddress); IStableSwapPoolETH(poolAddress).remove_liquidity(amount, minAmounts); uint256 lpTokenBalanceAfter = IERC20(lpTokenAddress).balanceOf(address(this)); uint256[N_COINS] memory coinsBalancesAfter = _getCoinsBalances(poolAddress); _compareCoinsBalances(coinsBalancesBefore, coinsBalancesAfter, minAmounts); require(lpTokenBalanceBefore.sub(amount) == lpTokenBalanceAfter, "LP_TOKEN_AMT_MISMATCH"); } /// @notice Withdraw liquidity from Curve pool /// @dev Calls to external contract /// @dev We trust sender to send a true curve poolAddress. If it's not the case it will fail in the remove_liquidity_one_coin part. /// @param poolAddress token addresses /// @param tokenAmount Amount of LP tokens to burn in the withdrawal /// @param i Index value of the coin to withdraw /// @param minAmount Minimum amount of coin to receive function withdrawOneCoin( address poolAddress, uint256 tokenAmount, int128 i, uint256 minAmount ) external onlyManager onlyRemoveLiquidity { address lpTokenAddress = _getLPTokenAndApprove(poolAddress, tokenAmount); address coin = IStableSwapPoolETH(poolAddress).coins(uint256(i)); uint256 lpTokenBalanceBefore = IERC20(lpTokenAddress).balanceOf(address(this)); uint256 coinBalanceBefore = _getBalance(coin); IStableSwapPoolETH(poolAddress).remove_liquidity_one_coin(tokenAmount, i, minAmount); uint256 lpTokenBalanceAfter = IERC20(lpTokenAddress).balanceOf(address(this)); uint256 coinBalanceAfter = _getBalance(coin); require(coinBalanceBefore < coinBalanceAfter, "BALANCE_MUST_INCREASE"); require( lpTokenBalanceBefore.sub(tokenAmount) == lpTokenBalanceAfter, "LP_TOKEN_AMT_MISMATCH" ); } function _getLPToken(address poolAddress) internal returns (address) { require(poolAddress != address(0), "INVALID_POOL_ADDRESS"); address registryAddress = addressProvider.get_registry(); address lpTokenAddress = IRegistry(registryAddress).get_lp_token(poolAddress); // If it's not registered in curve registry that should mean it's a factory pool (pool is also the LP Token) // https://curve.readthedocs.io/factory-pools.html?highlight=factory%20pools%20differ#lp-tokens if (lpTokenAddress == address(0)) { lpTokenAddress = poolAddress; } require(addressRegistry.checkAddress(lpTokenAddress, 0), "INVALID_LP_TOKEN"); return lpTokenAddress; } function _getBalance(address coin) internal returns (uint256) { uint256 balance; if (coin == ETH_REGISTRY_ADDRESS) { balance = address(this).balance; } else { balance = IERC20(coin).balanceOf(address(this)); } return balance; } function _getCoinsBalances(address poolAddress) internal returns (uint256[N_COINS] memory coinsBalances) { for (uint256 i = 0; i < N_COINS; i++) { address coin = IStableSwapPoolETH(poolAddress).coins(i); coinsBalances[i] = _getBalance(coin); } return coinsBalances; } function _compareCoinsBalances( uint256[N_COINS] memory balancesBefore, uint256[N_COINS] memory balancesAfter, uint256[N_COINS] memory amounts ) internal pure { for (uint256 i = 0; i < N_COINS; i++) { uint256 minAmount = amounts[i]; require(balancesAfter[i].sub(balancesBefore[i]) >= minAmount, "INVALID_BALANCE_CHANGE"); } } function _getLPTokenAndApprove(address poolAddress, uint256 amount) internal returns (address) { address lpTokenAddress = _getLPToken(poolAddress); if (lpTokenAddress != poolAddress) { _approve(IERC20(lpTokenAddress), poolAddress, amount); } return lpTokenAddress; } function _approve( IERC20 token, address spender, uint256 amount ) internal { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance > 0) { token.safeDecreaseAllowance(spender, currentAllowance); } token.safeIncreaseAllowance(spender, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IStableSwapPoolETH { /* solhint-disable func-name-mixedcase, var-name-mixedcase */ function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external payable; function remove_liquidity_imbalance(uint256[2] memory amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 amount, uint256[2] memory min_amounts) external; function remove_liquidity_one_coin( uint256 token_amount, int128 i, uint256 min_amount ) external; function coins(uint256 i) external returns (address); function balanceOf(address account) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IRegistry { /* solhint-disable func-name-mixedcase, var-name-mixedcase */ function get_lp_token(address pool) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IAddressProvider { /* solhint-disable func-name-mixedcase, var-name-mixedcase */ function get_registry() external view returns (address); } //SPDX-License-Identifier: MIT pragma solidity >=0.6.11 <=0.6.12; import "../interfaces/IAddressRegistry.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; //solhint-disable var-name-mixedcase contract BaseController { address public immutable manager; address public immutable accessControl; IAddressRegistry public immutable addressRegistry; bytes32 public immutable ADD_LIQUIDITY_ROLE = keccak256("ADD_LIQUIDITY_ROLE"); bytes32 public immutable REMOVE_LIQUIDITY_ROLE = keccak256("REMOVE_LIQUIDITY_ROLE"); bytes32 public immutable MISC_OPERATION_ROLE = keccak256("MISC_OPERATION_ROLE"); constructor(address _manager, address _accessControl, address _addressRegistry) public { require(_manager != address(0), "INVALID_ADDRESS"); require(_accessControl != address(0), "INVALID_ADDRESS"); require(_addressRegistry != address(0), "INVALID_ADDRESS"); manager = _manager; accessControl = _accessControl; addressRegistry = IAddressRegistry(_addressRegistry); } modifier onlyManager() { require(address(this) == manager, "NOT_MANAGER_ADDRESS"); _; } modifier onlyAddLiquidity() { require(AccessControl(accessControl).hasRole(ADD_LIQUIDITY_ROLE, msg.sender), "NOT_ADD_LIQUIDITY_ROLE"); _; } modifier onlyRemoveLiquidity() { require(AccessControl(accessControl).hasRole(REMOVE_LIQUIDITY_ROLE, msg.sender), "NOT_REMOVE_LIQUIDITY_ROLE"); _; } modifier onlyMiscOperation() { require(AccessControl(accessControl).hasRole(MISC_OPERATION_ROLE, msg.sender), "NOT_MISC_OPERATION_ROLE"); _; } } //SPDX-License-Identifier: MIT pragma solidity >=0.6.11 <=0.6.12; pragma experimental ABIEncoderV2; /** * @title Track addresses to be used in liquidity deployment * Any controller used, asset deployed, or pool tracked within the * system should be registered here */ interface IAddressRegistry { enum AddressTypes { Token, Controller, Pool } event RegisteredAddressAdded(address added); event RegisteredAddressRemoved(address removed); event AddedToRegistry(address[] addresses, AddressTypes); event RemovedFromRegistry(address[] addresses, AddressTypes); /// @notice Allows address with REGISTERED_ROLE to add a registered address /// @param _addr address to be added function addRegistrar(address _addr) external; /// @notice Allows address with REGISTERED_ROLE to remove a registered address /// @param _addr address to be removed function removeRegistrar(address _addr) external; /// @notice Allows array of addresses to be added to registry for certain index /// @param _addresses calldata array of addresses to be added to registry /// @param _index AddressTypes enum of index to add addresses to function addToRegistry(address[] calldata _addresses, AddressTypes _index) external; /// @notice Allows array of addresses to be removed from registry for certain index /// @param _addresses calldata array of addresses to be removed from registry /// @param _index AddressTypes enum of index to remove addresses from function removeFromRegistry(address[] calldata _addresses, AddressTypes _index) external; /// @notice Allows array of all addresses for certain index to be returned /// @param _index AddressTypes enum of index to be returned /// @return address[] memory of addresses from index function getAddressForType(AddressTypes _index) external view returns (address[] memory); /// @notice Allows checking that one address exists in certain index /// @param _addr address to be checked /// @param _index AddressTypes index to check address against /// @return bool tells whether address exists or not function checkAddress(address _addr, uint256 _index) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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; } }
@notice Withdraw liquidity from Curve pool @dev Calls to external contract @dev We trust sender to send a true curve poolAddress. If it's not the case it will fail in the remove_liquidity_imbalance part. @param poolAddress Token addresses @param amounts List of amounts of underlying coins to withdraw @param maxBurnAmount Maximum amount of LP token to burn in the withdrawal
function withdrawImbalance( address poolAddress, uint256[N_COINS] memory amounts, uint256 maxBurnAmount ) external onlyManager onlyRemoveLiquidity { address lpTokenAddress = _getLPTokenAndApprove(poolAddress, maxBurnAmount); uint256 lpTokenBalanceBefore = IERC20(lpTokenAddress).balanceOf(address(this)); uint256[N_COINS] memory coinsBalancesBefore = _getCoinsBalances(poolAddress); IStableSwapPoolETH(poolAddress).remove_liquidity_imbalance(amounts, maxBurnAmount); uint256 lpTokenBalanceAfter = IERC20(lpTokenAddress).balanceOf(address(this)); uint256[N_COINS] memory coinsBalancesAfter = _getCoinsBalances(poolAddress); _compareCoinsBalances(coinsBalancesBefore, coinsBalancesAfter, amounts); require(lpTokenBalanceBefore.sub(lpTokenBalanceAfter) <= maxBurnAmount, "LP_COST_TOO_HIGH"); }
11,934,493
[ 1, 1190, 9446, 4501, 372, 24237, 628, 22901, 2845, 225, 23665, 358, 3903, 6835, 225, 1660, 10267, 5793, 358, 1366, 279, 638, 8882, 2845, 1887, 18, 971, 518, 1807, 486, 326, 648, 518, 903, 2321, 316, 326, 1206, 67, 549, 372, 24237, 67, 381, 12296, 1087, 18, 225, 2845, 1887, 3155, 6138, 225, 30980, 987, 434, 30980, 434, 6808, 276, 9896, 358, 598, 9446, 225, 943, 38, 321, 6275, 18848, 3844, 434, 511, 52, 1147, 358, 18305, 316, 326, 598, 9446, 287, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 598, 9446, 1170, 12296, 12, 203, 3639, 1758, 2845, 1887, 16, 203, 3639, 2254, 5034, 63, 50, 67, 3865, 706, 55, 65, 3778, 30980, 16, 203, 3639, 2254, 5034, 943, 38, 321, 6275, 203, 565, 262, 3903, 1338, 1318, 1338, 3288, 48, 18988, 24237, 288, 203, 3639, 1758, 12423, 1345, 1887, 273, 389, 588, 14461, 1345, 1876, 12053, 537, 12, 6011, 1887, 16, 943, 38, 321, 6275, 1769, 203, 203, 3639, 2254, 5034, 12423, 1345, 13937, 4649, 273, 467, 654, 39, 3462, 12, 9953, 1345, 1887, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 63, 50, 67, 3865, 706, 55, 65, 3778, 276, 9896, 38, 26488, 4649, 273, 389, 588, 39, 9896, 38, 26488, 12, 6011, 1887, 1769, 203, 203, 3639, 467, 30915, 12521, 2864, 1584, 44, 12, 6011, 1887, 2934, 4479, 67, 549, 372, 24237, 67, 381, 12296, 12, 8949, 87, 16, 943, 38, 321, 6275, 1769, 203, 203, 3639, 2254, 5034, 12423, 1345, 13937, 4436, 273, 467, 654, 39, 3462, 12, 9953, 1345, 1887, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 63, 50, 67, 3865, 706, 55, 65, 3778, 276, 9896, 38, 26488, 4436, 273, 389, 588, 39, 9896, 38, 26488, 12, 6011, 1887, 1769, 203, 203, 3639, 389, 9877, 39, 9896, 38, 26488, 12, 71, 9896, 38, 26488, 4649, 16, 276, 9896, 38, 26488, 4436, 16, 30980, 1769, 203, 203, 3639, 2583, 12, 9953, 1345, 13937, 4649, 18, 1717, 12, 9953, 1345, 13937, 4436, 13, 1648, 943, 38, 321, 6275, 2 ]
./full_match/42220/0x5A36B5BeA23721ED3b6154a095F17D10FF130E7A/sources/CeloFarmsPool.sol
Withdraw tokens from STAKING.
function withdraw(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "withdraw: not good"); require(user.nextWithdrawalUntil <= block.timestamp, "Withdrawal locked"); updatePool(0); uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); user.nextWithdrawalUntil = block.timestamp.add(withdrawalInterval); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); emit Withdraw(msg.sender, _amount); }
16,336,393
[ 1, 1190, 9446, 2430, 628, 2347, 14607, 1360, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 20, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 2583, 12, 1355, 18, 4285, 1190, 9446, 287, 9716, 1648, 1203, 18, 5508, 16, 315, 1190, 9446, 287, 8586, 8863, 203, 3639, 1089, 2864, 12, 20, 1769, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 1345, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 3639, 309, 12, 9561, 405, 374, 13, 288, 203, 5411, 19890, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 4634, 1769, 203, 5411, 729, 18, 4285, 1190, 9446, 287, 9716, 273, 1203, 18, 5508, 18, 1289, 12, 1918, 9446, 287, 4006, 1769, 203, 3639, 289, 203, 3639, 309, 24899, 8949, 405, 374, 13, 288, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 5411, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 289, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 1345, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // 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((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not linked to a scheduled payment
uint256 public paymentsNextIndex;
451,086
[ 1, 23725, 787, 622, 770, 404, 16, 358, 1699, 584, 358, 999, 9755, 23725, 63, 20, 65, 364, 8938, 716, 854, 486, 8459, 358, 279, 9755, 5184, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 25754, 2134, 1016, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@manifoldxyz/libraries-solidity/contracts/access/IAdminControl.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/CreatorExtension.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/ICreatorExtensionTokenURI.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./IManifoldERC721Edition.sol"; /** * Manifold ERC721 Edition Controller Implementation */ contract ManifoldERC721Edition is CreatorExtension, ICreatorExtensionTokenURI, IManifoldERC721Edition, ReentrancyGuard { using Strings for uint256; struct IndexRange { uint256 startIndex; uint256 count; } mapping(address => mapping(uint256 => string)) _tokenPrefix; mapping(address => mapping(uint256 => uint256)) _maxSupply; mapping(address => mapping(uint256 => uint256)) _totalSupply; mapping(address => mapping(uint256 => IndexRange[])) _indexRanges; mapping(address => uint256) _currentSeries; /** * @dev Only allows approved admins to call the specified function */ modifier creatorAdminRequired(address creator) { require(IAdminControl(creator).isAdmin(msg.sender), "Must be owner or admin of creator contract"); _; } function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorExtension, IERC165) returns (bool) { return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || interfaceId == type(IManifoldERC721Edition).interfaceId || CreatorExtension.supportsInterface(interfaceId); } /** * @dev See {IManifoldERC721Edition-totalSupply}. */ function totalSupply(address creator, uint256 series) external view override returns(uint256) { return _totalSupply[creator][series]; } /** * @dev See {IManifoldERC721Edition-maxSupply}. */ function maxSupply(address creator, uint256 series) external view override returns(uint256) { return _maxSupply[creator][series]; } /** * @dev See {IManifoldERC721Edition-createSeries}. */ function createSeries(address creator, uint256 maxSupply_, string calldata prefix) external override creatorAdminRequired(creator) returns(uint256) { _currentSeries[creator] += 1; uint256 series = _currentSeries[creator]; _maxSupply[creator][series] = maxSupply_; _tokenPrefix[creator][series] = prefix; emit SeriesCreated(msg.sender, creator, series, maxSupply_); return series; } /** * @dev See {IManifoldERC721Edition-latestSeries}. */ function latestSeries(address creator) external view override returns(uint256) { return _currentSeries[creator]; } /** * See {IManifoldERC721Edition-setTokenURIPrefix}. */ function setTokenURIPrefix(address creator, uint256 series, string calldata prefix) external override creatorAdminRequired(creator) { require(series > 0 && series <= _currentSeries[creator], "Invalid series"); _tokenPrefix[creator][series] = prefix; } /** * @dev See {ICreatorExtensionTokenURI-tokenURI}. */ function tokenURI(address creator, uint256 tokenId) external view override returns (string memory) { (uint256 series, uint256 index) = _tokenSeriesAndIndex(creator, tokenId); return string(abi.encodePacked(_tokenPrefix[creator][series], (index+1).toString())); } /** * @dev See {IManifoldERC721Edition-mint}. */ function mint(address creator, uint256 series, address recipient, uint16 count) external override nonReentrant creatorAdminRequired(creator) { require(count > 0, "Invalid amount requested"); require(_totalSupply[creator][series]+count <= _maxSupply[creator][series], "Too many requested"); uint256[] memory tokenIds = IERC721CreatorCore(creator).mintExtensionBatch(recipient, count); _updateIndexRanges(creator, series, tokenIds[0], count); } /** * @dev See {IManifoldERC721Edition-mint}. */ function mint(address creator, uint256 series, address[] calldata recipients) external override nonReentrant creatorAdminRequired(creator) { require(recipients.length > 0, "Invalid amount requested"); require(_totalSupply[creator][series]+recipients.length <= _maxSupply[creator][series], "Too many requested"); uint256 startIndex = IERC721CreatorCore(creator).mintExtension(recipients[0]); for (uint256 i = 1; i < recipients.length; i++) { IERC721CreatorCore(creator).mintExtension(recipients[i]); } _updateIndexRanges(creator, series, startIndex, recipients.length); } /** * @dev Update the index ranges, which is used to figure out the index from a tokenId */ function _updateIndexRanges(address creator, uint256 series, uint256 startIndex, uint256 count) internal { IndexRange[] storage indexRanges = _indexRanges[creator][series]; if (indexRanges.length == 0) { indexRanges.push(IndexRange(startIndex, count)); } else { IndexRange storage lastIndexRange = indexRanges[indexRanges.length-1]; if ((lastIndexRange.startIndex + lastIndexRange.count) == startIndex) { lastIndexRange.count += count; } else { indexRanges.push(IndexRange(startIndex, count)); } } _totalSupply[creator][series] += count; } /** * @dev Index from tokenId */ function _tokenSeriesAndIndex(address creator, uint256 tokenId) internal view returns(uint256, uint256) { require(_currentSeries[creator] > 0, "Invalid token"); for (uint series=1; series <= _currentSeries[creator]; series++) { IndexRange[] memory indexRanges = _indexRanges[creator][series]; uint256 offset; for (uint i = 0; i < indexRanges.length; i++) { IndexRange memory currentIndex = indexRanges[i]; if (tokenId < currentIndex.startIndex) break; if (tokenId >= currentIndex.startIndex && tokenId < currentIndex.startIndex + currentIndex.count) { return (series, tokenId - currentIndex.startIndex + offset); } offset += currentIndex.count; } } revert("Invalid token"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Base creator extension variables */ abstract contract CreatorExtension is ERC165 { /** * @dev Legacy extension interface identifiers * * {IERC165-supportsInterface} needs to return 'true' for this interface * in order backwards compatible with older creator contracts */ bytes4 constant internal LEGACY_EXTENSION_INTERFACE = 0x7005caad; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == LEGACY_EXTENSION_INTERFACE || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 pragma solidity ^0.8.0; /// @author: manifold.xyz /** * Manifold ERC721 Edition Controller interface */ interface IManifoldERC721Edition { event SeriesCreated(address caller, address creator, uint256 series, uint256 maxSupply); /** * @dev Create a new series. Returns the series id. */ function createSeries(address creator, uint256 maxSupply, string calldata prefix) external returns(uint256); /** * @dev Get the latest series created. */ function latestSeries(address creator) external view returns(uint256); /** * @dev Set the token uri prefix */ function setTokenURIPrefix(address creator, uint256 series, string calldata prefix) external; /** * @dev Mint NFTs to a single recipient */ function mint(address creator, uint256 series, address recipient, uint16 count) external; /** * @dev Mint NFTS to the recipients */ function mint(address creator, uint256 series, address[] calldata recipients) external; /** * @dev Total supply of editions */ function totalSupply(address creator, uint256 series) external view returns(uint256); /** * @dev Max supply of editions */ function maxSupply(address creator, uint256 series) external view returns(uint256); } // 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.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); } // 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; } }
* @dev See {IManifoldERC721Edition-maxSupply}./
function maxSupply(address creator, uint256 series) external view override returns(uint256) { return _maxSupply[creator][series]; }
6,155,505
[ 1, 9704, 288, 3445, 304, 17081, 654, 39, 27, 5340, 41, 1460, 17, 1896, 3088, 1283, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 943, 3088, 1283, 12, 2867, 11784, 16, 2254, 5034, 4166, 13, 3903, 1476, 3849, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 327, 389, 1896, 3088, 1283, 63, 20394, 6362, 10222, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; import "./TCI_Contract.sol"; //---------------------------------------------------- //------------------ Invoice ------------------------- //---------------------------------------------------- contract Invoice_Contract{ /********** Definition of the data **********/ struct Invoice{ bytes32 amount; bytes32 currency; bytes32 dueAt; bytes32 issueAt; address sellerAddress; address buyerAddress; bool sellerHasValidate; bool buyerHasValidate; bool sellerGotPaid; bool HasTCI; bool InModifcation; bool HasBackUp; uint indexSeller; uint indexBuyer; } struct IndexTmp{ uint tmp_IndexSeller; } Invoice public _invoice; IndexTmp public _indexTmp; TCI_Contract public _tci; /********** Restriction **********/ modifier sellerOwnly(){ if(msg.sender != _invoice.sellerAddress) throw; _; } modifier IsValidate(){ if(!_invoice.sellerHasValidate && !_invoice.buyerHasValidate) throw; _; } /********** Events **********/ //For the payement in ether event sendAmount (address indexed _to, bytes32 indexed _value); /********** Constructor **********/ function Invoice_Contract (bytes32 amount, bytes32 currency, bytes32 dueAt, bytes32 issueAt, address sellerAddress, address buyerAddress, uint indexSeller, uint indexBuyer){ _invoice.amount = amount; _invoice.currency = currency; _invoice.dueAt = dueAt; _invoice.issueAt = issueAt; _invoice.sellerAddress = sellerAddress; _invoice.buyerAddress = buyerAddress; _invoice.indexSeller = indexSeller; _invoice.indexBuyer = indexBuyer; } function secondInitialisation(bool sellerHasValidate){ if(sellerHasValidate){ _invoice.sellerHasValidate = true; _invoice.buyerHasValidate = false; } else{ _invoice.sellerHasValidate = false; _invoice.buyerHasValidate = true; } } /********** Accessors **********/ function setInModification (bool value){ _invoice.InModifcation = value; } function getInModification() constant returns(bool){ return _invoice.InModifcation; } function setHasBackUp (bool value){ _invoice.HasBackUp = value; } function getIndexSeller() constant returns(uint){ return _invoice.indexSeller; } function getIndexBuyer() constant returns(uint){ return _invoice.indexBuyer; } function get_Tmp_indexSeller() constant returns(uint){ return _indexTmp.tmp_IndexSeller; } function getSellerHasValidate() constant returns(bool){ return _invoice.sellerHasValidate; } function getBuyerHasValidate() constant returns(bool){ return _invoice.buyerHasValidate; } function getAmount() constant returns(bytes32){ return _invoice.amount; } function getDueAt() constant returns(bytes32){ return _invoice.dueAt; } function getCounterpartAddress(bool IsSeller) constant returns (address){ if(IsSeller){ return _invoice.buyerAddress; } else{ return _invoice.sellerAddress; } } function getSellerGotPaid () public constant returns (bool){ return (_invoice.sellerGotPaid); } function setHasValidate (bool value){ _invoice.sellerHasValidate = value; _invoice.buyerHasValidate = value; } /********** Creation of TCI **********/ function createTCI(bytes32 idTransaction, bytes32 amount, bytes32 currency){ _invoice.HasTCI = true; _tci = new TCI_Contract(idTransaction, amount, currency); } /*function HasTciOrNot() public constant returns(bool){ return _invoice.HasTCI; }*/ /********** Display contract **********/ function displayContract() public constant returns (bytes32, bytes32, bytes32, bytes32, address, address, bool, bool, bool, bool, uint, uint){ return (_invoice.amount, _invoice.currency, _invoice.dueAt, _invoice.issueAt, _invoice.sellerAddress, _invoice.buyerAddress, _invoice.sellerHasValidate, _invoice.buyerHasValidate, _invoice.sellerGotPaid, _invoice.HasTCI, _invoice.indexSeller, _invoice.indexBuyer); } function displayContract_2() public constant returns (bool, bool){ return(_invoice.InModifcation, _invoice.HasBackUp); } function displayContractTCI() public constant returns (bool, bytes32, bytes32, bytes32){ return _tci.displayContractTCI(); } /********** Validation **********/ function Validation(){ if(_invoice.sellerHasValidate){ _invoice.buyerHasValidate = true; } else{ _invoice.sellerHasValidate = true; } } /********** restore **********/ function restore (bytes32 amount, bytes32 dueAt){ _invoice.amount = amount; _invoice.dueAt = dueAt; _invoice.buyerHasValidate = true; _invoice.sellerHasValidate = true; } /********** Paid **********/ function gotPaid() { //IsValidate() _invoice.sellerGotPaid = true; //_tci.SetStatusPayement(true); } /********** TCI defaultPayment **********/ function defaultPayment(bool IsVerified){ _tci.defaultPayment(IsVerified); } /********** Modification **********/ function modifcation(bytes32 dueDate, bytes32 amount, bool IsSeller, uint tmp_IndexSeller){ _invoice.dueAt = dueDate; _invoice.amount = amount; _indexTmp.tmp_IndexSeller = tmp_IndexSeller; //Restart the validation process if(IsSeller){ _invoice.buyerHasValidate = false; _invoice.sellerHasValidate = true; } else{ _invoice.sellerHasValidate = false; _invoice.buyerHasValidate = true; } //Cancel the insurance if(_invoice.HasTCI){ _invoice.HasTCI = false; } } /********** Premium **********/ // /!\ The contract must have an amout of ether /*function premiumPayement (string tci_amount) sellerOwnly(){ if(!_invoice.owner.send(parseInt(tci_amount))){ _invoice.IsPaid = false; } else{ _invoice.IsPaid = true; sendAmount(_invoice.owner, tci_amount); } }*/ }
/ /!\ The contract must have an amout of etherfunction premiumPayement (string tci_amount) sellerOwnly(){
if(!_invoice.owner.send(parseInt(tci_amount))){ _invoice.IsPaid = false; Premium }
7,211,770
[ 1, 19, 342, 24440, 1021, 6835, 1297, 1240, 392, 2125, 659, 434, 225, 2437, 915, 23020, 5077, 9148, 820, 261, 1080, 1715, 77, 67, 8949, 13, 29804, 5460, 715, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 1377, 309, 12, 5, 67, 16119, 18, 8443, 18, 4661, 12, 2670, 1702, 12, 5111, 77, 67, 8949, 3719, 15329, 203, 3639, 389, 16119, 18, 2520, 16507, 350, 273, 629, 31, 203, 225, 453, 2764, 5077, 203, 1377, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// https://github.com/iearn-finance/globes/blob/master/contracts/controllers/StrategyControllerV1.sol pragma solidity ^0.6.7; pragma experimental ABIEncoderV2; import "./interfaces/controller.sol"; import "./lib/erc20.sol"; import "./lib/safe-math.sol"; import "./interfaces/globe.sol"; import "./interfaces/globe-converter.sol"; import "./interfaces/onesplit.sol"; import "./interfaces/strategy.sol"; import "./interfaces/converter.sol"; contract ControllerV4 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant burn = 0x000000000000000000000000000000000000dEaD; address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; address public governance; address public strategist; address public devfund; address public treasury; address public timelock; // Convenience fee 0.1% uint256 public convenienceFee = 100; uint256 public constant convenienceFeeMax = 100000; mapping(address => address) public globes; // takes lp address and returns associated globe mapping(address => address) public strategies; // takes lp and returns associated strategy mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public approvedGlobeConverters; uint256 public split = 500; uint256 public constant max = 10000; constructor( address _governance, address _strategist, address _timelock, address _devfund, address _treasury ) public { governance = _governance; strategist = _strategist; timelock = _timelock; devfund = _devfund; treasury = _treasury; } function setDevFund(address _devfund) public { require(msg.sender == governance, "!governance"); devfund = _devfund; } function setTreasury(address _treasury) public { require(msg.sender == governance, "!governance"); treasury = _treasury; } function setStrategist(address _strategist) public { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); require(_split <= max, "numerator cannot be greater than denominator"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setGlobe(address _token, address _globe) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(globes[_token] == address(0), "globe"); globes[_token] = _globe; } function approveGlobeConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedGlobeConverters[_converter] = true; } function revokeGlobeConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedGlobeConverters[_converter] = false; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); require(strategies[_token] != _strategy, "cannot revoke active strategy"); approvedStrategies[_token][_strategy] = false; } function setConvenienceFee(uint256 _convenienceFee) external { require(msg.sender == timelock, "!timelock"); convenienceFee = _convenienceFee; } function setStrategy(address _token, address _strategy) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(approvedStrategies[_token][_strategy] == true, "!approved"); address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return IStrategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); IStrategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IStrategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = IStrategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn( _token, _want, _balance, parts, 0 ); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == globes[_token], "!globe"); IStrategy(strategies[_token]).withdraw(_amount); } // Function to swap between globes function swapExactGlobeForGlobe( address _fromGlobe, // From which Globe address _toGlobe, // To which Globe uint256 _fromGlobeAmount, // How much globe tokens to swap uint256 _toGlobeMinAmount, // How much globe tokens you'd like at a minimum address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); // Only return last response for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedGlobeConverters[_targets[i]], "!converter"); } address _fromGlobeToken = IGlobe(_fromGlobe).token(); address _toGlobeToken = IGlobe(_toGlobe).token(); // Get pTokens from msg.sender IERC20(_fromGlobe).safeTransferFrom( msg.sender, address(this), _fromGlobeAmount ); // Calculate how much underlying // is the amount of pTokens worth uint256 _fromGlobeUnderlyingAmount = _fromGlobeAmount .mul(IGlobe(_fromGlobe).getRatio()) .div(10**uint256(IGlobe(_fromGlobe).decimals())); // Call 'withdrawForSwap' on Globe's current strategy if Globe // doesn't have enough initial capital. // This has moves the funds from the strategy to the Globe's // 'earnable' amount. Enabling 'free' withdrawals uint256 _fromGlobeAvailUnderlying = IERC20(_fromGlobeToken).balanceOf( _fromGlobe ); if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) { IStrategy(strategies[_fromGlobeToken]).withdrawForSwap( _fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying) ); } // Withdraw from Globe // Note: this is free since its still within the "earnable" amount // as we transferred the access IERC20(_fromGlobe).safeApprove(_fromGlobe, 0); IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount); IGlobe(_fromGlobe).withdraw(_fromGlobeAmount); // Calculate fee uint256 _fromUnderlyingBalance = IERC20(_fromGlobeToken).balanceOf( address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2)); } // Executes sequence of logic for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } // Deposit into new Globe uint256 _toBal = IERC20(_toGlobeToken).balanceOf(address(this)); IERC20(_toGlobeToken).safeApprove(_toGlobe, 0); IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal); IGlobe(_toGlobe).deposit(_toBal); // Send Globe Tokens to user uint256 _toGlobeBal = IGlobe(_toGlobe).balanceOf(address(this)); if (_toGlobeBal < _toGlobeMinAmount) { revert("!min-globe-amount"); } IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal); return _toGlobeBal; } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { 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) } } } }
Convenience fee 0.1%
contract ControllerV4 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant burn = 0x000000000000000000000000000000000000dEaD; address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; address public governance; address public strategist; address public devfund; address public treasury; address public timelock; uint256 public convenienceFee = 100; uint256 public constant convenienceFeeMax = 100000; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public approvedGlobeConverters; uint256 public split = 500; uint256 public constant max = 10000; constructor( address _governance, address _strategist, address _timelock, address _devfund, address _treasury ) public { governance = _governance; strategist = _strategist; timelock = _timelock; devfund = _devfund; treasury = _treasury; } function setDevFund(address _devfund) public { require(msg.sender == governance, "!governance"); devfund = _devfund; } function setTreasury(address _treasury) public { require(msg.sender == governance, "!governance"); treasury = _treasury; } function setStrategist(address _strategist) public { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); require(_split <= max, "numerator cannot be greater than denominator"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setGlobe(address _token, address _globe) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(globes[_token] == address(0), "globe"); globes[_token] = _globe; } function approveGlobeConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedGlobeConverters[_converter] = true; } function revokeGlobeConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedGlobeConverters[_converter] = false; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); require(strategies[_token] != _strategy, "cannot revoke active strategy"); approvedStrategies[_token][_strategy] = false; } function setConvenienceFee(uint256 _convenienceFee) external { require(msg.sender == timelock, "!timelock"); convenienceFee = _convenienceFee; } function setStrategy(address _token, address _strategy) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(approvedStrategies[_token][_strategy] == true, "!approved"); address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function setStrategy(address _token, address _strategy) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(approvedStrategies[_token][_strategy] == true, "!approved"); address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } } else { function balanceOf(address _token) external view returns (uint256) { return IStrategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); IStrategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IStrategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = IStrategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn( _token, _want, _balance, parts, 0 ); } function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == globes[_token], "!globe"); IStrategy(strategies[_token]).withdraw(_amount); } function swapExactGlobeForGlobe( address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedGlobeConverters[_targets[i]], "!converter"); } address _fromGlobeToken = IGlobe(_fromGlobe).token(); address _toGlobeToken = IGlobe(_toGlobe).token(); msg.sender, address(this), _fromGlobeAmount ); .mul(IGlobe(_fromGlobe).getRatio()) .div(10**uint256(IGlobe(_fromGlobe).decimals())); _fromGlobe ); if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) { IStrategy(strategies[_fromGlobeToken]).withdrawForSwap( _fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying) ); } IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount); IGlobe(_fromGlobe).withdraw(_fromGlobeAmount); address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2)); } for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } IERC20(_toGlobeToken).safeApprove(_toGlobe, 0); IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal); IGlobe(_toGlobe).deposit(_toBal); if (_toGlobeBal < _toGlobeMinAmount) { revert("!min-globe-amount"); } IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal); return _toGlobeBal; } function swapExactGlobeForGlobe( address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedGlobeConverters[_targets[i]], "!converter"); } address _fromGlobeToken = IGlobe(_fromGlobe).token(); address _toGlobeToken = IGlobe(_toGlobe).token(); msg.sender, address(this), _fromGlobeAmount ); .mul(IGlobe(_fromGlobe).getRatio()) .div(10**uint256(IGlobe(_fromGlobe).decimals())); _fromGlobe ); if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) { IStrategy(strategies[_fromGlobeToken]).withdrawForSwap( _fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying) ); } IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount); IGlobe(_fromGlobe).withdraw(_fromGlobeAmount); address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2)); } for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } IERC20(_toGlobeToken).safeApprove(_toGlobe, 0); IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal); IGlobe(_toGlobe).deposit(_toBal); if (_toGlobeBal < _toGlobeMinAmount) { revert("!min-globe-amount"); } IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal); return _toGlobeBal; } IERC20(_fromGlobe).safeTransferFrom( uint256 _fromGlobeUnderlyingAmount = _fromGlobeAmount uint256 _fromGlobeAvailUnderlying = IERC20(_fromGlobeToken).balanceOf( function swapExactGlobeForGlobe( address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedGlobeConverters[_targets[i]], "!converter"); } address _fromGlobeToken = IGlobe(_fromGlobe).token(); address _toGlobeToken = IGlobe(_toGlobe).token(); msg.sender, address(this), _fromGlobeAmount ); .mul(IGlobe(_fromGlobe).getRatio()) .div(10**uint256(IGlobe(_fromGlobe).decimals())); _fromGlobe ); if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) { IStrategy(strategies[_fromGlobeToken]).withdrawForSwap( _fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying) ); } IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount); IGlobe(_fromGlobe).withdraw(_fromGlobeAmount); address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2)); } for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } IERC20(_toGlobeToken).safeApprove(_toGlobe, 0); IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal); IGlobe(_toGlobe).deposit(_toBal); if (_toGlobeBal < _toGlobeMinAmount) { revert("!min-globe-amount"); } IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal); return _toGlobeBal; } IERC20(_fromGlobe).safeApprove(_fromGlobe, 0); uint256 _fromUnderlyingBalance = IERC20(_fromGlobeToken).balanceOf( function swapExactGlobeForGlobe( address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedGlobeConverters[_targets[i]], "!converter"); } address _fromGlobeToken = IGlobe(_fromGlobe).token(); address _toGlobeToken = IGlobe(_toGlobe).token(); msg.sender, address(this), _fromGlobeAmount ); .mul(IGlobe(_fromGlobe).getRatio()) .div(10**uint256(IGlobe(_fromGlobe).decimals())); _fromGlobe ); if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) { IStrategy(strategies[_fromGlobeToken]).withdrawForSwap( _fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying) ); } IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount); IGlobe(_fromGlobe).withdraw(_fromGlobeAmount); address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2)); } for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } IERC20(_toGlobeToken).safeApprove(_toGlobe, 0); IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal); IGlobe(_toGlobe).deposit(_toBal); if (_toGlobeBal < _toGlobeMinAmount) { revert("!min-globe-amount"); } IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal); return _toGlobeBal; } function swapExactGlobeForGlobe( address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedGlobeConverters[_targets[i]], "!converter"); } address _fromGlobeToken = IGlobe(_fromGlobe).token(); address _toGlobeToken = IGlobe(_toGlobe).token(); msg.sender, address(this), _fromGlobeAmount ); .mul(IGlobe(_fromGlobe).getRatio()) .div(10**uint256(IGlobe(_fromGlobe).decimals())); _fromGlobe ); if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) { IStrategy(strategies[_fromGlobeToken]).withdrawForSwap( _fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying) ); } IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount); IGlobe(_fromGlobe).withdraw(_fromGlobeAmount); address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2)); } for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } IERC20(_toGlobeToken).safeApprove(_toGlobe, 0); IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal); IGlobe(_toGlobe).deposit(_toBal); if (_toGlobeBal < _toGlobeMinAmount) { revert("!min-globe-amount"); } IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal); return _toGlobeBal; } uint256 _toBal = IERC20(_toGlobeToken).balanceOf(address(this)); uint256 _toGlobeBal = IGlobe(_toGlobe).balanceOf(address(this)); function swapExactGlobeForGlobe( address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedGlobeConverters[_targets[i]], "!converter"); } address _fromGlobeToken = IGlobe(_fromGlobe).token(); address _toGlobeToken = IGlobe(_toGlobe).token(); msg.sender, address(this), _fromGlobeAmount ); .mul(IGlobe(_fromGlobe).getRatio()) .div(10**uint256(IGlobe(_fromGlobe).decimals())); _fromGlobe ); if (_fromGlobeAvailUnderlying < _fromGlobeUnderlyingAmount) { IStrategy(strategies[_fromGlobeToken]).withdrawForSwap( _fromGlobeUnderlyingAmount.sub(_fromGlobeAvailUnderlying) ); } IERC20(_fromGlobe).safeApprove(_fromGlobe, _fromGlobeAmount); IGlobe(_fromGlobe).withdraw(_fromGlobeAmount); address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromGlobeToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromGlobeToken).safeTransfer(treasury, _convenienceFee.div(2)); } for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } IERC20(_toGlobeToken).safeApprove(_toGlobe, 0); IERC20(_toGlobeToken).safeApprove(_toGlobe, _toBal); IGlobe(_toGlobe).deposit(_toBal); if (_toGlobeBal < _toGlobeMinAmount) { revert("!min-globe-amount"); } IGlobe(_toGlobe).transfer(msg.sender, _toGlobeBal); return _toGlobeBal; } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { require(_target != address(0), "!target"); 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 { revert(add(response, 0x20), size) } } } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { require(_target != address(0), "!target"); 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 { revert(add(response, 0x20), size) } } } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { require(_target != address(0), "!target"); 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 { revert(add(response, 0x20), size) } } } }
7,263,213
[ 1, 14700, 14036, 374, 18, 21, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6629, 58, 24, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 1071, 5381, 18305, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 565, 1758, 1071, 5945, 1127, 273, 374, 14626, 25, 5292, 1919, 42, 24, 69, 20, 2733, 22, 39, 7616, 25, 39, 74, 3787, 73, 21, 8906, 9383, 24, 41, 6334, 26, 1441, 39, 758, 73, 20, 41, 31, 203, 203, 565, 1758, 1071, 314, 1643, 82, 1359, 31, 203, 565, 1758, 1071, 609, 1287, 376, 31, 203, 565, 1758, 1071, 4461, 74, 1074, 31, 203, 565, 1758, 1071, 9787, 345, 22498, 31, 203, 565, 1758, 1071, 1658, 292, 975, 31, 203, 203, 565, 2254, 5034, 1071, 13553, 14667, 273, 2130, 31, 203, 565, 2254, 5034, 1071, 5381, 13553, 14667, 2747, 273, 25259, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1758, 3719, 1071, 19414, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 20412, 1585, 15127, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 20412, 13499, 73, 24615, 31, 203, 203, 565, 2254, 5034, 1071, 1416, 273, 6604, 31, 203, 565, 2254, 5034, 1071, 5381, 943, 273, 12619, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 75, 1643, 82, 1359, 16, 203, 3639, 1758, 389, 701, 1287, 376, 16, 203, 3639, 1758, 389, 8584, 292, 975, 2 ]
// SPDX-License-Identifier: MIT // GO TO LINE 1904 TO SEE WHERE THE TOKEN CONTRACT STARTS // 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; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <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/IERC721Metadata.sol pragma solidity >=0.6.2 <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/IERC721Enumerable.sol pragma solidity >=0.6.2 <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/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File "@openzeppelin/contracts/finance/PaymentSplitter.sol"; pragma solidity >=0.6.2 <0.8.0; /** * @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 { // solhint-disable-next-line max-line-length 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_); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Own one of only 12,500 programmatically generated and minted Wicked Willy's. You will own a unique collectible, selected randomly from over 1.25bn possible combinations. // They are so wickedly rare, that only a tiny % of the global population will ever be able to own one. Secure your own Wicked Willy while you can! // You can visit our website https://wickedwillysnft.com or get the team on https://twitter.com/wickedwillysnft pragma solidity ^0.7.0; pragma abicoder v2; contract WickedWillys is ERC721, PaymentSplitter, Ownable { using SafeMath for uint256; // Constants uint public constant maxTokenPurchase = 20; uint256 public constant MAX_TOKENS = 12500; // Variables uint private tokenReserve = 200; // Reserved up front for the teams effort and for giveaways/promotional activity uint256 public tokenPrice = 30000000000000000; // 0.03 ETH bool public saleIsActive = false; // Withdraw Addresses address[] private teamWallets = [ 0x214B56E7121aB36977F9B4920E04263d1FAabb8c, // 70 0x39010C2E22281629E9E7aC94f5c78dB38FDD8a7E // 30 ]; uint256[] private teamShares = [70,30]; // To be decided string public TOKEN_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN TOKENS ARE ALL SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE event licenseisLocked(string _licenseText); constructor() PaymentSplitter(teamWallets, teamShares) ERC721("Wicked Willys", "WILLYS") {} // Make sale Active/Inactive function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } // Return Sale Active/Inactive function getSalesState() public view returns (bool){ return saleIsActive; } function reserveTokens(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= tokenReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } tokenReserve = tokenReserve.sub(_reserveAmount); } // Just in case ETH does something silly function setTokenPrice(uint256 newPrice) public onlyOwner { tokenPrice = newPrice; } function setProvenanceHash(string memory provenanceHash) public onlyOwner { TOKEN_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } 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; } } // Returns the license for tokens function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "Choose a token within range"); return LICENSE_TEXT; } // Change the license function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "The license is already locked"); LICENSE_TEXT = _license; } // Locks the license to prevent further changes function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } function getBalance() public view onlyOwner returns (uint){ uint balance = address(this).balance; return balance; } function withdrawAll() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } // Withdraw balance to wallets per share allocation function withdrawShares() public onlyOwner { for (uint256 i = 0; i < teamWallets.length; i++) { address payable wallet = payable(teamWallets[i]); release(wallet); } } function mintToken(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Token"); require(numberOfTokens > 0 && numberOfTokens <= maxTokenPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Tokens"); require(msg.value >= tokenPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(msg.sender, mintIndex); } } } }
Constants Variables Withdraw Addresses To be decided Make sale Active/Inactive
contract WickedWillys is ERC721, PaymentSplitter, Ownable { using SafeMath for uint256; uint public constant maxTokenPurchase = 20; uint256 public constant MAX_TOKENS = 12500; bool public saleIsActive = false; address[] private teamWallets = [ ]; uint256[] private teamShares = [70,30]; event licenseisLocked(string _licenseText); constructor() PaymentSplitter(teamWallets, teamShares) ERC721("Wicked Willys", "WILLYS") {} function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function getSalesState() public view returns (bool){ return saleIsActive; } function reserveTokens(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= tokenReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } tokenReserve = tokenReserve.sub(_reserveAmount); } function reserveTokens(address _to, uint256 _reserveAmount) public onlyOwner { uint supply = totalSupply(); require(_reserveAmount > 0 && _reserveAmount <= tokenReserve, "Not enough reserve left for team"); for (uint i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } tokenReserve = tokenReserve.sub(_reserveAmount); } function setTokenPrice(uint256 newPrice) public onlyOwner { tokenPrice = newPrice; } function setProvenanceHash(string memory provenanceHash) public onlyOwner { TOKEN_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } else { function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "Choose a token within range"); return LICENSE_TEXT; } function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "The license is already locked"); LICENSE_TEXT = _license; } function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } function getBalance() public view onlyOwner returns (uint){ uint balance = address(this).balance; return balance; } function withdrawAll() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } function withdrawShares() public onlyOwner { for (uint256 i = 0; i < teamWallets.length; i++) { address payable wallet = payable(teamWallets[i]); release(wallet); } } function withdrawShares() public onlyOwner { for (uint256 i = 0; i < teamWallets.length; i++) { address payable wallet = payable(teamWallets[i]); release(wallet); } } function mintToken(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Token"); require(numberOfTokens > 0 && numberOfTokens <= maxTokenPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Tokens"); require(msg.value >= tokenPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(msg.sender, mintIndex); } } } function mintToken(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Token"); require(numberOfTokens > 0 && numberOfTokens <= maxTokenPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Tokens"); require(msg.value >= tokenPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(msg.sender, mintIndex); } } } function mintToken(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Token"); require(numberOfTokens > 0 && numberOfTokens <= maxTokenPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_TOKENS, "Purchase would exceed max supply of Tokens"); require(msg.value >= tokenPrice.mul(numberOfTokens), "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(msg.sender, mintIndex); } } } }
1,149,591
[ 1, 2918, 23536, 3423, 9446, 23443, 2974, 506, 2109, 13898, 4344, 272, 5349, 8857, 19, 24384, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 678, 1200, 329, 59, 330, 715, 87, 353, 4232, 39, 27, 5340, 16, 12022, 26738, 16, 14223, 6914, 288, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 1071, 5381, 943, 1345, 23164, 273, 4200, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 8412, 55, 273, 2593, 12483, 31, 203, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 629, 31, 203, 203, 565, 1758, 8526, 3238, 5927, 26558, 2413, 273, 306, 203, 565, 308, 31, 203, 203, 565, 2254, 5034, 8526, 3238, 5927, 24051, 273, 306, 7301, 16, 5082, 15533, 203, 203, 377, 203, 565, 871, 8630, 291, 8966, 12, 1080, 389, 12687, 1528, 1769, 203, 203, 565, 3885, 1435, 203, 3639, 12022, 26738, 12, 10035, 26558, 2413, 16, 5927, 24051, 13, 203, 3639, 4232, 39, 27, 5340, 2932, 59, 1200, 329, 678, 330, 715, 87, 3113, 315, 59, 2627, 7076, 55, 7923, 203, 203, 203, 203, 565, 2618, 203, 565, 445, 9668, 30746, 1119, 1435, 1071, 1338, 5541, 288, 203, 3639, 272, 5349, 2520, 3896, 273, 401, 87, 5349, 2520, 3896, 31, 203, 565, 289, 203, 203, 565, 445, 1322, 5408, 1119, 1435, 1071, 1476, 1135, 261, 6430, 15329, 203, 3639, 327, 272, 5349, 2520, 3896, 31, 203, 565, 289, 203, 377, 203, 565, 445, 20501, 5157, 12, 2867, 389, 869, 16, 2254, 5034, 389, 455, 6527, 6275, 13, 1071, 1338, 5541, 288, 540, 203, 3639, 2254, 14467, 273, 2078, 3088, 1283, 5621, 203, 3639, 2583, 24899, 455, 6527, 6275, 405, 374, 597, 389, 2 ]
./full_match/5/0xD6ee3B39dD53b753E3253Befa40222602406409B/sources/src/Vault.sol
@notice Emitted when the system is set to private @param origin Origin of the transaction (tx.origin) @param sender Sender of the call (msg.sender)
event SystemPrivate(address indexed origin, address indexed sender);
1,876,190
[ 1, 1514, 11541, 1347, 326, 2619, 353, 444, 358, 3238, 225, 4026, 18040, 434, 326, 2492, 261, 978, 18, 10012, 13, 225, 5793, 15044, 434, 326, 745, 261, 3576, 18, 15330, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 2332, 6014, 12, 2867, 8808, 4026, 16, 1758, 8808, 5793, 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 ]
pragma solidity ^0.4.19; import "../interfaces/StoreInterface.sol"; import "./SafeMath.sol"; library RewardsStorageProxy { using SafeMath for uint256; /** * @notice Dividends functions can only be called through the proof network * @notice In its current form, the proof network consists of the Cryptofiat and the AMP Manager contracts * @dev Implement the onlyAuthorized function when writing the ownership model */ modifier onlyAuthorized() { _; } //getters function getCurrentPoolIndex(address _store) public view returns(uint256) { return StoreInterface(_store).getUint(keccak256("rewards.currentPoolIndex")); } function getCurrentEpoch(address _store) public view returns(uint256) { return StoreInterface(_store).getUint(keccak256("rewards.currentEpoch")); } function getCurrentPoolBalance(address _store) public view returns(uint256) { return StoreInterface(_store).getUint(keccak256("rewards.currentPoolBalance")); } function getNthPoolBalance(address _store, uint256 _index) public view returns(uint256) { return StoreInterface(_store).getUint(keccak256("rewards.nthPoolBalance", _index)); } function getNthPoolRemainingDividends(address _store, uint256 _index) public view returns(uint256) { return StoreInterface(_store).getUint(keccak256("rewards.nthPoolRemainingBalance", _index)); } function getAccountLastWithdrawal(address _store, address _account) public view returns(uint256) { return StoreInterface(_store).getUint(keccak256("rewards.accounts.lastWithdrawal", _account)); } function getBlocksPerEpoch(address _store) public view returns(uint256) { return StoreInterface(_store).getUint(keccak256("rewards.blocksPerEpoch")); } //setters function setCurrentPoolIndex(address _store, uint256 _value) public { StoreInterface(_store).setUint(keccak256("rewards.currentPoolIndex"), _value); } function setCurrentEpoch(address _store, uint256 _value) public { StoreInterface(_store).setUint(keccak256("rewards.currentEpoch"), _value); } function setCurrentPoolBalance(address _store, uint256 _value) public { StoreInterface(_store).setUint(keccak256("rewards.currentPoolBalance"), _value); } function setNthPoolBalance(address _store, uint256 _index, uint256 _value) public { StoreInterface(_store).setUint(keccak256("rewards.nthPoolBalance", _index), _value); } function setNthPoolRemainingDividends(address _store, uint256 _index, uint256 _value) public { StoreInterface(_store).setUint(keccak256("rewards.nthPoolRemainingBalance", _index), _value); } function setAccountLastWithdrawal(address _store, address _account, uint256 _value) public { StoreInterface(_store).setUint(keccak256("rewards.accounts.lastWithdrawal", _account), _value); } function setBlocksPerEpoch(address _store, uint256 _value) public { StoreInterface(_store).setUint(keccak256("rewards.blocksPerEpoch"), _value); } //helpers function incrementCurrentPoolIndex(address _store, uint256 _amount) public { uint256 newValue = StoreInterface(_store).getUint(keccak256("rewards.currentPoolIndex")).add(_amount); StoreInterface(_store).setUint(keccak256("rewards.currentPoolIndex"), newValue); } function incrementCurrentEpoch(address _store, uint256 _amount) public { uint256 newValue = StoreInterface(_store).getUint(keccak256("rewards.currentEpoch")).add(_amount); StoreInterface(_store).setUint(keccak256("rewards.currentEpoch"), newValue); } function incrementCurrentPoolBalance(address _store, uint256 _amount) public { uint256 newValue = StoreInterface(_store).getUint(keccak256("rewards.currentPoolBalance")).add(_amount); StoreInterface(_store).setUint(keccak256("rewards.currentPoolBalance"), newValue); } }
* @notice Dividends functions can only be called through the proof network @notice In its current form, the proof network consists of the Cryptofiat and the AMP Manager contracts @dev Implement the onlyAuthorized function when writing the ownership model/
{ _; }
1,059,735
[ 1, 7244, 350, 5839, 4186, 848, 1338, 506, 2566, 3059, 326, 14601, 2483, 225, 657, 2097, 783, 646, 16, 326, 14601, 2483, 20915, 434, 326, 22752, 792, 77, 270, 471, 326, 432, 4566, 8558, 20092, 225, 10886, 326, 1338, 15341, 445, 1347, 7410, 326, 23178, 938, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 288, 203, 3639, 389, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x6f86331aB21D09BB7Fd98d4082a4b949500dAf54/sources/MYT2_Exchange.sol
* Retrieve the token balance of any single address./
function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; }
16,624,071
[ 1, 5767, 326, 1147, 11013, 434, 1281, 2202, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 389, 10061, 1887, 13, 203, 3639, 1476, 203, 3639, 1071, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 15533, 203, 565, 289, 203, 27699, 203, 21281, 27699, 377, 203, 27699, 27699, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xf043809056AC2492c4aaE6317705f751082c0Db1/sources/ELONGATE.sol
2% from total supply maxTransactionAmountTxn
maxTransactionAmount = (totalSupply) / 50;
4,222,915
[ 1, 22, 9, 628, 2078, 14467, 943, 3342, 6275, 13789, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 943, 3342, 6275, 273, 261, 4963, 3088, 1283, 13, 342, 6437, 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.21 <0.7.0; import "./Migrations.sol"; pragma experimental ABIEncoderV2; contract Applicants { enum ExpDurationMonth {Zero, January, February, March, April, May, June, July, August, September, October, November, December} enum SkillLevel {Default, Beginner, Intermediate, Advanced} enum ProficiencyLevel {Default, Novice, Fluent, Intermediate, Advanced, Superior} // Customized ACTFL Proficiency (American Council on the Teaching of Foreign Language) struct Applicant { // Personal Information string name; uint nameChanges; string physicalAddress; string location; string nationality; bool exists; // Experiences string[] experienceIdentifiers; // SKills string[] skillIdentifiers; // Identifications string[] identificationIdentifiers; // Salary Preference Stipend salaryFlooring; Stipend salaryCeiling; } struct Language { string name; ProficiencyLevel spokenProficiency; ProficiencyLevel writtenProficiency; bool exists; } struct Skill { string name; SkillLevel level; bool exists; } struct Experience { string positionTitle; string companyName; ExpDurationStart start; ExpDurationEnd end; string specialization; string role; string country; string industry; string positionLevel; Stipend monthlySalary; string description; bool exists; } struct ExpDurationEnd { uint year; Applicants.ExpDurationMonth ExpDurationMonth; bool present; } struct ExpDurationStart { uint year; Applicants.ExpDurationMonth ExpDurationMonth; } struct Stipend { string currency; uint amount; } struct Identification { string filename; bool exists; } mapping (address => Applicant) applicants; address[] applicantAccts; mapping (string => Experience) experiences; mapping (string => Skill) skills; mapping (string => Identification) identifications; event ApplicantsAppend (address indexed _address); // Identifications function updateIdentification( address _address, string memory _fileName ) public returns (bool, string memory) { string memory tempFileNameIdentifier = string(abi.encodePacked(addressToString(_address), "-", _fileName)); if (msg.sender == _address) { Identification storage identification = identifications[tempFileNameIdentifier]; identification.filename = _fileName; identification.exists = true; bool _identificationFound; uint _identificationIndex; (_identificationFound, _identificationIndex) = identificationFound(_address, tempFileNameIdentifier, ""); if (_identificationFound == false && identifications[tempFileNameIdentifier].exists) { applicants[_address].identificationIdentifiers.push(tempFileNameIdentifier); } return (true, ""); } else { return (false, "Account holder does not exists or you are not the holder of this account."); } } function identificationFound(address _address, string memory _fileName, string memory _administrativeCode) public view returns (bool, uint) { if ((msg.sender == _address) || (compareStrings(_administrativeCode, "sudo"))) { bool found = false; uint index = 0; for (uint i = 0; i < applicants[_address].identificationIdentifiers.length; i++) { if (compareStrings(applicants[_address].identificationIdentifiers[i], _fileName)) { found = true; index = i; } } if (found) { return (true, index); } else { return (false, 0); } } else { return (false, 0); } } function getIdentificationDetails(address _address, string memory _fileName, string memory _administrativeCode) view public returns (Identification memory) { if ((compareStrings(_administrativeCode,"sudo") && msg.sender != _address) || (msg.sender == _address)) { bool _identificationExists; uint _identificationIndex; (_identificationExists, _identificationIndex) = identificationFound(_address, _fileName, _administrativeCode); if (identifications[_fileName].exists == true && _identificationExists) { return identifications[_fileName]; } } } function deleteIdentification(address _address, string memory _fileName) public returns (bool, string memory) { if (_address == msg.sender) { bool _idenficationFound; uint _identificationIndex; (_idenficationFound, _identificationIndex) = identificationFound(_address, _fileName, ""); if (_idenficationFound == true && identifications[_fileName].exists) { identifications[_fileName].exists = false; for (uint i = _identificationIndex; i<applicants[_address].identificationIdentifiers.length-1; i++){ applicants[_address].identificationIdentifiers[i] = applicants[_address].identificationIdentifiers[i+1]; } delete applicants[_address].identificationIdentifiers[applicants[_address].identificationIdentifiers.length-1]; applicants[_address].identificationIdentifiers.length-=1; return (true, ""); } return (true, ""); } else { return (false, "One must be able to change own identifications by logging in with one's own address"); } } // Applicants function setApplicant (address _address, string memory _name, string memory _physicalAddress, string memory _location, string memory _nationality, string memory _administrativeCode) public returns (bool) { if (!applicants[_address].exists && compareStrings(_administrativeCode,"sudo")) { Applicant storage applicant = applicants[_address]; applicant.name = _name; applicant.nameChanges = 0; if (compareStrings(_physicalAddress,"")) { applicants[_address].physicalAddress = "---"; } else { applicants[_address].physicalAddress = _physicalAddress; } if (compareStrings(_physicalAddress,"")) { applicants[_address].nationality = "---"; } else { applicants[_address].nationality = _nationality; } if (compareStrings(_location,"")) { applicants[_address].location = "---"; } else { applicants[_address].location = _location; } applicants[_address].salaryFlooring = createStipend("Php", 0); applicants[_address].salaryCeiling = createStipend("Php", 0); applicant.exists = true; applicantAccts.push(_address); emit Applicants.ApplicantsAppend(_address); return true; } else { return false; } } function getApplicants(string memory _administrativeCode) view public returns(address[] memory) { if (compareStrings(_administrativeCode,"sudo")) { return applicantAccts; } } function getApplicantProfile(address _address, string memory _administrativeCode) view public returns(Applicant memory) { if ((compareStrings(_administrativeCode,"sudo") && msg.sender != _address) || (msg.sender == _address)) { return applicants[_address]; } } function updateName (address _address, string memory _name) public returns (bool, uint, string memory) { if (applicants[_address].exists && msg.sender == _address) { if (applicants[_address].nameChanges < 3) { applicants[_address].name = _name; applicants[_address].nameChanges+=1; return (true, 3-applicants[_address].nameChanges, "Name changed!" ); } else { return (false, applicants[_address].nameChanges, "This account exceeds in the number of name changes."); } } else { return (false, 0, "Account holder does not exists or you are not the holder of this account."); } } function updateAddress(address _address, string memory _physicalAddress) public returns (bool, string memory) { if (applicants[_address].exists && msg.sender == _address) { applicants[_address].physicalAddress = _physicalAddress; return (true, ""); } else { return (false, "Account holder does not exists or you are not the holder of this account."); } } function updateNationality(address _address, string memory _nationality) public returns (bool, string memory) { if (applicants[_address].exists && msg.sender == _address) { applicants[_address].nationality = _nationality; return (true, ""); } else { return (false, "Account holder does not exists or you are not the holder of this account."); } } // Salary Preference Functions function setSalaryFlooring(address _address, string memory _currency, uint _amount) public returns (bool, string memory){ if (msg.sender == _address) { if (compareStrings(_currency,"")) { applicants[_address].salaryFlooring = createStipend("---", _amount); return (true, ""); } else { applicants[_address].salaryFlooring = createStipend(_currency, _amount); return (true, ""); } } else { return (false, "Account holder does not exists or you are not the holder of this account."); } } function setSalaryCeiling(address _address, string memory _currency, uint _amount) public returns (bool, string memory){ if (msg.sender == _address) { if (compareStrings(_currency,"")) { applicants[_address].salaryCeiling = createStipend("---", _amount); return (true, ""); } else { applicants[_address].salaryCeiling = createStipend(_currency, _amount); return (true, ""); } } else { return (false, "Account holder does not exists or you are not the holder of this account."); } } // Skill Functions function getSkillDetails(address _address, string memory _skillName, string memory _administrativeCode) view public returns (Skill memory) { if ((compareStrings(_administrativeCode,"sudo") && msg.sender != _address) || (msg.sender == _address)) { bool _skillExists; uint _skillIndex; (_skillExists, _skillIndex) = skillFound(_address, _skillName, _administrativeCode); if (skills[_skillName].exists == true && _skillExists) { return skills[_skillName]; } } } function updateSkill( address _address, string memory _skillName, uint _level ) public returns (bool, string memory) { string memory tempSkillIdentifier = string(abi.encodePacked(addressToString(_address), "-", _skillName)); if (msg.sender == _address) { Skill storage skill = skills[tempSkillIdentifier]; skill.name = _skillName; skill.level = selectSkillLevel(_level); skill.exists = true; bool _skillFound; uint _skillIndex; (_skillFound, _skillIndex) = skillFound(_address, tempSkillIdentifier, ""); if (_skillFound == false && skills[tempSkillIdentifier].exists) { applicants[_address].skillIdentifiers.push(tempSkillIdentifier); } return (true, ""); } else { return (false, "Account holder does not exists or you are not the holder of this account."); } } function skillFound(address _address, string memory _skillName, string memory _administrativeCode) public view returns (bool, uint) { if ((msg.sender == _address) || (compareStrings(_administrativeCode, "sudo"))) { bool found = false; uint index = 0; for (uint i = 0; i < applicants[_address].skillIdentifiers.length; i++) { if (compareStrings(applicants[_address].skillIdentifiers[i], _skillName)) { found = true; index = i; } } if (found) { return (true, index); } else { return (false, 0); } } else { return (false, 0); } } function deleteSkill(address _address, string memory _skillName) public returns (bool, string memory) { if (_address == msg.sender) { bool _skillFound; uint _skillIndex; (_skillFound, _skillIndex) = skillFound(_address, _skillName, ""); if (_skillFound == true && skills[_skillName].exists) { skills[_skillName].exists = false; for (uint i = _skillIndex; i<applicants[_address].skillIdentifiers.length-1; i++){ applicants[_address].skillIdentifiers[i] = applicants[_address].skillIdentifiers[i+1]; } delete applicants[_address].skillIdentifiers[applicants[_address].skillIdentifiers.length-1]; applicants[_address].skillIdentifiers.length-=1; return (true, ""); } return (true, ""); } else { return (false, "One must be able to change own skills by logging in with one's own address"); } } // Experience Functions function getExperienceDetails(address _address, string memory _experienceName, string memory _administrativeCode) view public returns (Experience memory) { if ((compareStrings(_administrativeCode,"sudo") && msg.sender != _address) || (msg.sender == _address)) { bool _experienceExists; uint _experienceIndex; (_experienceExists, _experienceIndex) = experienceFound(_address, _experienceName, _administrativeCode); if (experiences[_experienceName].exists == true && _experienceExists) { return experiences[_experienceName]; } } } function updateExperience( address _address, string memory _experienceName, string[] memory _details, uint[] memory _start, uint[] memory _end, bool _present, string memory _currency, uint _amount ) public returns (bool, string memory) { string memory tempExperienceIdentifier = string(abi.encodePacked(addressToString(_address), "-", _experienceName)); if (msg.sender == _address) { Experience storage experience = experiences[tempExperienceIdentifier]; experience.positionTitle = _details[0]; experience.companyName = _details[1]; experience.specialization = _details[2]; experience.role = _details[3]; experience.country = _details[4]; experience.industry = _details[5]; experience.positionLevel = _details[6]; experience.description = _details[7]; experience.start = createExpDurationStart(_start[0], _start[1]); experience.end = createExpDurationEnd(_end[0], _end[1], _present); experience.monthlySalary = createStipend(_currency, _amount); experience.exists = true; bool _experienceFound; uint _experienceIndex; (_experienceFound, _experienceIndex) = experienceFound(_address, tempExperienceIdentifier, ""); if (_experienceFound == false && experiences[tempExperienceIdentifier].exists) { applicants[_address].experienceIdentifiers.push(tempExperienceIdentifier); } return (true, ""); } else { return (false, "Account holder does not exists or you are not the holder of this account."); } } function experienceFound(address _address, string memory _experienceName, string memory _administrativeCode) public view returns (bool, uint) { if ((msg.sender == _address) || (compareStrings(_administrativeCode, "sudo"))) { bool found = false; uint index = 0; for (uint i = 0; i < applicants[_address].experienceIdentifiers.length; i++) { if (compareStrings(applicants[_address].experienceIdentifiers[i], _experienceName)) { found = true; index = i; } } if (found) { return (true, index); } else { return (false, 0); } } else { return (false, 0); } } function deleteExperience(address _address, string memory _experienceName) public returns (bool, string memory) { if (_address == msg.sender) { bool _experienceFound; uint _experienceIndex; (_experienceFound, _experienceIndex) = experienceFound(_address, _experienceName, ""); if (_experienceFound == true && experiences[_experienceName].exists) { experiences[_experienceName].exists = false; for (uint i = _experienceIndex; i<applicants[_address].experienceIdentifiers.length-1; i++){ applicants[_address].experienceIdentifiers[i] = applicants[_address].experienceIdentifiers[i+1]; } delete applicants[_address].experienceIdentifiers[applicants[_address].experienceIdentifiers.length-1]; applicants[_address].experienceIdentifiers.length-=1; return (true, ""); } return (true, ""); } else { return (false, "One must be able to change own experiences by logging in with one's own address"); } } // Auxiliary Functions function compareStrings (string memory a, string memory b) public pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } function addressToString (address x) public pure returns (string memory) { bytes32 value = bytes32(uint256(x)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = '0'; str[1] = 'x'; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))]; } return string(str); } function selectExpDurationMonth (uint _monthIndex) internal pure returns (Applicants.ExpDurationMonth) { if (_monthIndex == 1) return Applicants.ExpDurationMonth.January; if (_monthIndex == 2) return Applicants.ExpDurationMonth.February; if (_monthIndex == 3) return Applicants.ExpDurationMonth.March; if (_monthIndex == 4) return Applicants.ExpDurationMonth.April; if (_monthIndex == 5) return Applicants.ExpDurationMonth.May; if (_monthIndex == 6) return Applicants.ExpDurationMonth.June; if (_monthIndex == 7) return Applicants.ExpDurationMonth.July; if (_monthIndex == 8) return Applicants.ExpDurationMonth.August; if (_monthIndex == 9) return Applicants.ExpDurationMonth.September; if (_monthIndex == 10) return Applicants.ExpDurationMonth.October; if (_monthIndex == 11) return Applicants.ExpDurationMonth.November; if (_monthIndex == 12) return Applicants.ExpDurationMonth.December; return Applicants.ExpDurationMonth.Zero; } function selectSkillLevel (uint _levelIndex) internal pure returns (Applicants.SkillLevel) { if (_levelIndex == 1) return Applicants.SkillLevel.Beginner; if (_levelIndex == 2) return Applicants.SkillLevel.Intermediate; if (_levelIndex == 3) return Applicants.SkillLevel.Advanced; return Applicants.SkillLevel.Default; } function createExpDurationStart (uint _year, uint _month) internal pure returns (Applicants.ExpDurationStart memory) { return Applicants.ExpDurationStart(uint(_year), selectExpDurationMonth(_month)); } function createExpDurationEnd (uint _year, uint _month, bool _present) internal pure returns (Applicants.ExpDurationEnd memory) { return Applicants.ExpDurationEnd(uint(_year), selectExpDurationMonth(_month), _present); } function createStipend (string memory _currency, uint _amount) internal pure returns (Applicants.Stipend memory){ return Applicants.Stipend(_currency, _amount); } }
Auxiliary Functions
function compareStrings (string memory a, string memory b) public pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); }
1,017,548
[ 1, 21981, 20606, 15486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3400, 7957, 261, 1080, 3778, 279, 16, 533, 3778, 324, 13, 1071, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 69, 20349, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 70, 3719, 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 ]
pragma solidity ^0.4.23; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/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: contracts/ArbitrageETHStaking.sol /** * @title ArbitrageETHStaking * @dev The ArbitrageETHStaking contract staking Ether(ETH) tokens. * Here is stored all function and data of user stakes in contract. * Staking is configured for 1%. */ contract ArbitrageETHStaking is Ownable { using SafeMath for uint256; /*============================== = EVENTS = ==============================*/ event onPurchase( address indexed customerAddress, uint256 etherIn, uint256 contractBal, uint256 poolFee, uint timestamp ); event onWithdraw( address indexed customerAddress, uint256 etherOut, uint256 contractBal, uint timestamp ); /*** STORAGE ***/ mapping(address => uint256) internal personalFactorLedger_; // personal factor ledger mapping(address => uint256) internal balanceLedger_; // users balance ledger // Configurations uint256 minBuyIn = 0.001 ether; // can't buy less then 0.0001 ETH uint256 stakingPrecent = 1; uint256 internal globalFactor = 10e21; // global factor uint256 constant internal constantFactor = 10e21 * 10e21; // constant factor /// @dev Forward all Ether in buy() function function() external payable { buy(); } // @dev Buy in staking pool, transfer ethereum in the contract, pay 1% fee function buy() public payable { address _customerAddress = msg.sender; require(msg.value >= minBuyIn, "should be more the 0.0001 ether sent"); uint256 _etherBeforeBuyIn = getBalance().sub(msg.value); uint256 poolFee; // Check is not a first buy in if (_etherBeforeBuyIn != 0) { // Add 1% fee of the buy to the staking pool poolFee = msg.value.mul(stakingPrecent).div(100); // Increase amount of eth everyone else owns uint256 globalIncrease = globalFactor.mul(poolFee) / _etherBeforeBuyIn; globalFactor = globalFactor.add(globalIncrease); } balanceLedger_[_customerAddress] = ethBalanceOf(_customerAddress).add(msg.value).sub(poolFee); personalFactorLedger_[_customerAddress] = constantFactor / globalFactor; emit onPurchase(_customerAddress, msg.value, getBalance(), poolFee, now); } /** * @dev Withdraw selected amount of ethereum from the contract back to user, * update the balance. * @param _sellEth - Amount of ethereum to withdraw from contract */ function withdraw(uint256 _sellEth) public { address _customerAddress = msg.sender; // User must have enough eth and cannot sell 0 require(_sellEth > 0, "user cant spam transactions with 0 value"); require(_sellEth <= ethBalanceOf(_customerAddress), "user cant withdraw more then he holds "); // Transfer balance and update user ledgers _customerAddress.transfer(_sellEth); balanceLedger_[_customerAddress] = ethBalanceOf(_customerAddress).sub(_sellEth); personalFactorLedger_[_customerAddress] = constantFactor / globalFactor; emit onWithdraw(_customerAddress, _sellEth, getBalance(), now); } // @dev Withdraw all the ethereum user holds in the contract, set balance to 0 function withdrawAll() public { address _customerAddress = msg.sender; // Set the sell amount to the user's full balance, don't sell if empty uint256 _sellEth = ethBalanceOf(_customerAddress); require(_sellEth > 0, "user cant call withdraw, when holds nothing"); // Transfer balance and update user ledgers _customerAddress.transfer(_sellEth); balanceLedger_[_customerAddress] = 0; personalFactorLedger_[_customerAddress] = constantFactor / globalFactor; emit onWithdraw(_customerAddress, _sellEth, getBalance(), now); } /** * UI Logic - View Functions */ // @dev Returns contract ETH balance function getBalance() public view returns (uint256) { return address(this).balance; } // @dev Returns user ETH tokens balance in contract function ethBalanceOf(address _customerAddress) public view returns (uint256) { // Balance ledger * personal factor * globalFactor / constantFactor return balanceLedger_[_customerAddress].mul(personalFactorLedger_[_customerAddress]).mul(globalFactor) / constantFactor; } }
personal factor ledger
mapping(address => uint256) internal personalFactorLedger_;
1,808,616
[ 1, 29991, 5578, 16160, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 17816, 6837, 28731, 67, 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 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/Counters.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/introspection/IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: @openzeppelin/contracts/utils/Strings.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: contracts/INFTStaker.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Required interface of an ERC721 compliant contract. */ interface INFTStaker is IERC165 { struct Reward { address minter; uint256 amount; uint256 startBlock; uint256 endBlock; bool isStaked; } function rewardRecords(uint256 id) external view returns (address, uint256, uint256, uint256, bool); /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) external; } // File: contracts/Blockmon.sol pragma solidity ^0.6.1; contract Blockmon is ERC721, Ownable { using SafeERC20 for IERC20; using Counters for Counters.Counter; Counters.Counter private _rewardIds; string public _contractURI; IERC20 public token; INFTStaker public nft; // number of created mons (not counting merges) uint256 public numMonsCreated; // tinkerable variables uint256 public minStakeTime; uint256 public minStakeAmt; uint256 public tokenPrice; uint256 public series; uint256 public maxMons; uint256 public mergePrice; uint256 public mergeTime; uint256 public genMergeLag; bool public canMerge; struct Mon { address miner; uint256 unlockBlock; uint256 parent1; uint256 parent2; uint256 gen; uint256 amount; uint256 duration; uint256 powerBits; uint256 series; } mapping(uint256 => Mon) public monRecords; constructor(string memory name, string memory symbol) ERC721(name, symbol) public { minStakeAmt = 1; minStakeTime = 10000; tokenPrice = 1e18; } function _createNewMonster(address to, uint256 unlockBlock, uint256 parent1, uint256 parent2, uint256 gen, uint256 amount, uint256 duration // series is a global variable so no need to pass it in ) private { _rewardIds.increment(); uint256 currId = _rewardIds.current(); monRecords[currId] = Mon( to, unlockBlock, parent1, parent2, gen, amount, duration, uint256(blockhash(block.number-1))+amount+duration, series ); _safeMint(to, currId); } // Burn gem to get a new monster function mineMonster(uint256 gemId) public { require(nft.ownerOf(gemId) == msg.sender, "must use nft you own"); (, uint256 amount, uint256 start, uint256 end, ) = nft.rewardRecords(gemId); if (end == 0) { end = block.number; } require((end-start) >= minStakeTime, "nft is not ready"); require(amount >= minStakeAmt, "staked amt is not high enough"); require(numMonsCreated < maxMons, "no new mons out yet"); _createNewMonster(msg.sender, 0, 0, 0, 0, amount, end-start); numMonsCreated += 1; nft.burn(gemId); } // Directly purchase monster with the set token function buyMonster() public { require(numMonsCreated < maxMons, "no new mons out yet"); token.safeTransferFrom(msg.sender, address(this), tokenPrice); _createNewMonster(msg.sender, 0, 0, 0, 0, 0, 0); numMonsCreated += 1; } // Breed a monster // Only allowed during certain times function mergeMonsters(uint256 id1, uint256 id2) public { require(canMerge == true, "can't merge yet"); require(id1 != id2, "can't merge the same monster"); // get refs to structs Mon memory mon1 = monRecords[id1]; Mon memory mon2 = monRecords[id2]; // ensure they are valid for merging require(mon1.unlockBlock < block.number, "not ready yet"); require(mon2.unlockBlock < block.number, "not ready yet"); require(ownerOf(id1) == msg.sender, "need to own monster"); require(ownerOf(id2) == msg.sender, "need to own monster"); // set both parent monsters to the new unlock date monRecords[id1].unlockBlock = block.number + mergeTime + mon1.gen*genMergeLag; monRecords[id2].unlockBlock = block.number + mergeTime + mon2.gen*genMergeLag; // set numAncestors1 to be the minimum of both uint256 gen1 = mon1.gen; uint256 gen2 = mon2.gen; if (gen2 < gen1) { gen1 = gen2; } // mint the user their merged monster _createNewMonster( msg.sender, block.number + mergeTime + gen1*genMergeLag, id1, id2, gen1+1, mon1.amount + mon2.amount, mon1.duration + mon2.duration ); // Pay the merge fee token.safeTransferFrom(msg.sender, address(this), mergePrice); } function setMinStakeAmt(uint256 a) public onlyOwner { minStakeAmt = a; } function setMinStakeTime(uint256 t) public onlyOwner { minStakeTime = t; } function setTokenPrice(uint256 p) public onlyOwner { tokenPrice = p; } function setSeries(uint256 s) public onlyOwner { series = s; } function setMaxMons(uint256 m) public onlyOwner { maxMons = m; } function setMergePrice(uint256 p) public onlyOwner { mergePrice = p; } function setMergeTime(uint256 t) public onlyOwner { mergeTime = t; } function setGenMergeLag(uint256 g) public onlyOwner { genMergeLag = g; } function setCanMerge(bool b) public onlyOwner{ canMerge = b; } function setTokenAddress(address tokenAddress) public onlyOwner { token = IERC20(tokenAddress); } function setNFTAddress(address nftAddress) public onlyOwner { nft = INFTStaker(nftAddress); } function setBaseURI(string memory uri) public onlyOwner { _setBaseURI(uri); } function setContractURI(string memory uri) public onlyOwner { _contractURI = uri; } function moveTokens(address tokenAddress, address to, uint256 numTokens) public onlyOwner { IERC20 _token = IERC20(tokenAddress); _token.safeTransfer(to, numTokens); } function contractURI() public view returns (string memory) { return _contractURI; } function getTotalMons() public view returns (uint256) { return _rewardIds.current(); } }
* @title Counters @author Matt Condon (@shrugs) @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number of elements in a mapping, issuing ERC721 ids, or counting request ids. Include with `using Counters for Counters.Counter;` Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never directly accessed./
library Counters { using SafeMath for uint256; struct Counter { } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } }
231,028
[ 1, 18037, 225, 490, 4558, 735, 19752, 261, 36, 674, 8653, 564, 13, 225, 28805, 13199, 716, 848, 1338, 506, 28859, 578, 15267, 329, 635, 1245, 18, 1220, 848, 506, 1399, 425, 18, 75, 18, 358, 3298, 326, 1300, 434, 2186, 316, 279, 2874, 16, 3385, 22370, 4232, 39, 27, 5340, 3258, 16, 578, 22075, 590, 3258, 18, 12672, 598, 1375, 9940, 9354, 87, 364, 9354, 87, 18, 4789, 31, 68, 7897, 518, 353, 486, 3323, 358, 9391, 279, 8303, 2831, 3571, 598, 17071, 434, 1245, 16, 1375, 15016, 68, 848, 2488, 326, 288, 9890, 10477, 97, 9391, 866, 16, 1915, 1637, 12392, 16189, 18, 1220, 1552, 6750, 14025, 3434, 4084, 16, 316, 716, 326, 6808, 1375, 67, 1132, 68, 353, 5903, 5122, 15539, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 9354, 87, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 203, 565, 1958, 9354, 288, 203, 565, 289, 203, 203, 565, 445, 783, 12, 4789, 2502, 3895, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 3895, 6315, 1132, 31, 203, 565, 289, 203, 203, 565, 445, 5504, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 3895, 6315, 1132, 1011, 404, 31, 203, 565, 289, 203, 203, 565, 445, 15267, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 3895, 6315, 1132, 273, 3895, 6315, 1132, 18, 1717, 12, 21, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma ton-solidity >= 0.36.0; import "Base.sol"; import "./interfaces/IProposal.sol"; import "./interfaces/IPadawan.sol"; import "./interfaces/IDemiurge.sol"; import "./interfaces/ITokenRoot.sol"; import "./interfaces/ITokenWallet.sol"; contract Padawan is Base { uint32 constant ERROR_UNAUTHORIZED_CALLER = 110; uint32 constant ERROR_NOT_ENOUGH_VOTES = 111; uint32 constant ERROR_NO_MORE_THAN_ONE_RECLAIM_AT_A_TIME = 112; uint32 constant ERROR_NOT_A_USER_WALLET = 113; uint32 constant ERROR_MSG_VALUE_TOO_LOW = 114; uint32 constant ERROR_TOKEN_ACCOUNT_ALREADY_EXISTS = 115; uint32 constant ERROR_INVALID_ROOT_CALLER = 116; uint32 constant ERROR_ANSWER_ID_NOT_FOUND = 117; uint32 constant ERROR_ACCOUNT_DOES_NOT_EXIST = 118; uint32 constant ERROR_DEPOSIT_NOT_FOUND = 119; uint32 constant ERROR_CALLER_IS_NOT_DEPOOL = 120; uint32 constant ERROR_DEPOSIT_WITH_SUCH_ID_EXISTS = 121; uint32 constant ERROR_PENDING_DEPOSIT_ALREADY_EXISTS = 122; uint32 constant ERROR_INVALID_DEPLOYER = 123; struct Deposit { uint256 tokenId; address returnTo; uint64 amount; uint64 valuePerVote; bool approved; uint256 depool; } // ProposalDeployer address address static deployer; // User address address _ownerAddress; // Collection of Padawan's token accounts. // map [token root address] => account struct mapping (address => TipAccount) tokenAccounts; // Set of deposits of different currencies (crystals, tip tokens, depool stake) // map [createdAt] => Deposit struct mapping (uint32 => Deposit) deposits; // predefined TokenId for Crystals currency uint256 _crystalsID = 0; // Set of proposal address for which user is voted and which are not finalized yet. mapping(address => uint32) _activeProposals; // Set of proposal votes. // Used for easy querying locked votes. // map [votes] -> counter mapping(uint32 => uint32) _spentVotes; // Number of votes requested to reclaim uint32 _requestedVotes; // Total number of votes available to user. uint32 _totalVotes; // Number of votes that cannot be reclaimed until finish of one of active proposals. uint32 _lockedVotes; // Id of token deposit that is not approved yet. // If == 0, there is no pending deposits. uint32 _pendingDepositId; address _tokenRoot; event VoteRejected(uint64 pid, uint32 votes, uint16 ec); /* * Helpers */ modifier contractOnly() { require(msg.sender != address(0)); _; } modifier onlyOwner() { require(msg.sender == _ownerAddress, ERROR_NOT_A_USER_WALLET); _; } /* * Initialization */ constructor(address tokenRoot) public contractOnly { require(deployer == msg.sender, ERROR_INVALID_DEPLOYER); _tokenRoot = tokenRoot; IDemiurge(deployer).onPadawanDeploy{value: 1 ton}(tvm.pubkey()); _createTokenAccount(); } function initPadawan(address ownerAddress) external { require(msg.sender == deployer, ERROR_UNAUTHORIZED_CALLER); _ownerAddress = ownerAddress; } /* * Public Voting API */ /// @notice Allows user to vote for proposal. function voteFor(address proposal, bool choice, uint32 votes) external onlyOwner { optional(uint32) opt = _activeProposals.fetch(proposal); uint32 proposalVotes = opt.hasValue() ? opt.get() : 0; uint32 availableVotes = _totalVotes - proposalVotes; require(votes <= availableVotes, ERROR_NOT_ENOUGH_VOTES); if (!opt.hasValue()) { _activeProposals[proposal] = 0; } IProposal(proposal).voteFor{value: 0, flag: 64, bounce: true}(tvm.pubkey(), choice, votes); } /// @notice Called by Proposal smc in case if votes are accepted. function confirmVote(uint64 pid, uint32 deposit) external contractOnly { // pid - unused pid = pid; optional(uint32) opt = _activeProposals.fetch(msg.sender); require(opt.hasValue()); uint32 propVotes = opt.get(); uint32 newPropVotes = deposit + propVotes; _activeProposals[msg.sender] = newPropVotes; _deleteSpentVotes(propVotes); _spentVotes[newPropVotes] += 1; _updateLockedVotes(); // return change for `voteFor` back to user _ownerAddress.transfer(0, false, 64); } /// @notice Called by Proposal smc in case if votes are rejected. function rejectVote(uint64 pid, uint32 deposit, uint16 ec) external contractOnly { optional(uint32) opt = _activeProposals.fetch(msg.sender); require(opt.hasValue()); uint32 propVotes = opt.get(); if (propVotes == 0) { delete _activeProposals[msg.sender]; } _ownerAddress.transfer(0, false, 64); emit VoteRejected(pid, deposit, ec); } /// @notice Allows to withdraw unlocked user votes back in crystal or tons. /// @param votes - number of votes to reclaim. function reclaimDeposit(uint32 votes) external onlyOwner { require(msg.value >= DEPOSIT_TONS_FEE, ERROR_MSG_VALUE_TOO_LOW); require(votes <= _totalVotes, ERROR_NOT_ENOUGH_VOTES); _requestedVotes = votes; if (_requestedVotes <= _totalVotes - _lockedVotes) { _unlockDeposit(); } // need to query status of each active proposal optional(address, uint32) proposal = _activeProposals.min(); while (proposal.hasValue()) { (address addr, /* uint128 votes*/) = proposal.get(); IProposal(addr).queryStatus{value: QUERY_STATUS_FEE, bounce: true, flag: 1}(); proposal = _activeProposals.next(addr); } } /* * Groups API */ /// @notice Receives proposal status. Called by Proposal smc as an answer on queryStatus(). function updateStatus(uint64 pid, ProposalState state) external contractOnly { pid = pid; optional(uint32) opt = _activeProposals.fetch(msg.sender); require(opt.hasValue()); tvm.accept(); // if proposal is ended if (state >= ProposalState.Ended) { _deleteSpentVotes(opt.get()); _updateLockedVotes(); delete _activeProposals[msg.sender]; } if (_requestedVotes <= _totalVotes - _lockedVotes) { _unlockDeposit(); } } /* * Private functions */ function _deleteSpentVotes(uint32 votes) private { optional(uint32) spentOpt = _spentVotes.fetch(votes); if (spentOpt.hasValue()) { uint32 counter = spentOpt.get(); if (counter > 1) { _spentVotes[votes] = counter - 1; } else { delete _spentVotes[votes]; } } } /// @notice update locked votes function _updateLockedVotes() private inline { uint32 maxVotes = 0; optional(uint32, uint32) maxVotesOpt = _spentVotes.max(); if (maxVotesOpt.hasValue()) { (uint32 votes, ) = maxVotesOpt.get(); maxVotes = votes; } if (_lockedVotes != maxVotes) { _lockedVotes = maxVotes; } } function _unlockDeposit() private { uint32 origVotes = _requestedVotes; optional(uint32, Deposit) depo = deposits.max(); while (depo.hasValue()) { (uint32 createdAt, Deposit deposit) = depo.get(); if (_requestedVotes != 0) { uint32 votes = math.min(_requestedVotes, uint32(deposit.amount / deposit.valuePerVote)); uint64 value = uint64(deposit.valuePerVote * votes); if (deposit.tokenId == _crystalsID) { _ownerAddress.transfer(value, false, 0); // } else if (deposit.tokenId == _depoolID) { // // user can reclaim only all depool stake at once. // if (value >= deposit.amount) { // // address depool = address.makeAddrStd(0, deposit.depool); // // IDePool(depool).transferStake{value: 0.5 ton, flag: 1} // // (deposit.returnTo, deposit.amount); // } else { // (votes, value) = (0, 0); // } } else { TipAccount acc = tokenAccounts[address.makeAddrStd(0, deposit.tokenId)]; ITokenWallet(acc.addr).transfer{value: 0.1 ton + 0.1 ton} (deposit.returnTo, value, false, acc.addr); } deposit.amount -= math.min(value, deposit.amount); if (deposit.amount == 0) { delete deposits[createdAt]; } else { deposits[createdAt] = deposit; } _requestedVotes -= math.min(votes, _requestedVotes); } depo = deposits.prev(createdAt); } _totalVotes -= origVotes - _requestedVotes; } function _genId() private pure inline returns (uint32) { return uint32(now); } /* Receiving interface */ /// @notice Plain receiving of tons. receive() external { } /// @notice Accept income messages. fallback() external { } /// @notice Plain transfer of tons. function transferFunds(address to, uint128 val) external pure onlyOwner { to.transfer(val, true, 1); } /* * Public Deposits API */ /// @notice Allows to deposit tip3 tokens /// @param returnTo - address to which return tokens in case of reclaim request. /// @param tokenId - ID of deposited tip3 token (it is a std addr of TokenRoot smc). /// @param tokens - Number of tokens to deposit. function depositTokens( address returnTo, uint256 tokenId, uint64 tokens ) external onlyOwner { uint32 createdAt = _genId(); require(!deposits.exists(createdAt), ERROR_DEPOSIT_WITH_SUCH_ID_EXISTS); require(_pendingDepositId == 0, ERROR_PENDING_DEPOSIT_ALREADY_EXISTS); require(msg.value >= DEPOSIT_TOKENS_FEE, ERROR_MSG_VALUE_TOO_LOW); optional(TipAccount) opt = tokenAccounts.fetch(address.makeAddrStd(0, tokenId)); require(opt.hasValue(), ERROR_ACCOUNT_DOES_NOT_EXIST); TipAccount acc = opt.get(); _pendingDepositId = createdAt; ITokenWallet(acc.addr).getBalance_InternalOwner{value: 0, flag: 64, bounce: true} (tvm.functionId(onGetBalance)); deposits[createdAt] = Deposit(tokenId, returnTo, tokens, 0, false, 0); } /* * Private deposit functions */ function _convertDepositToVotes(uint32 queryId, uint64 price) private inline { optional(Deposit) opt = deposits.fetch(queryId); require(opt.hasValue(), ERROR_DEPOSIT_NOT_FOUND); Deposit depo = opt.get(); deposits[queryId].valuePerVote = price; _totalVotes += uint32(depo.amount / price); } function _findTokenAccount(address addr) private view inline returns (optional(address, TipAccount)) { optional(address, TipAccount) account = tokenAccounts.min(); while (account.hasValue()) { (address root, TipAccount acc) = account.get(); if (acc.addr == addr) { return account; } account = tokenAccounts.next(root); } return account; } function onGetBalance(uint128 balance) public contractOnly { optional(address, TipAccount) account = _findTokenAccount(msg.sender); require(account.hasValue(), ERROR_ACCOUNT_DOES_NOT_EXIST); require(_pendingDepositId != 0); (address root, TipAccount acc) = account.get(); uint128 prevBalance = acc.balance; tokenAccounts[root].balance = balance; optional(Deposit) opt = deposits.fetch(_pendingDepositId); require(opt.hasValue(), ERROR_DEPOSIT_NOT_FOUND); Deposit dep = opt.get(); if (balance >= dep.amount + prevBalance) { deposits[_pendingDepositId].approved = true; _convertDepositToVotes(_pendingDepositId, 1); // _ownerAddress.transfer(0, false, 64); } else { delete deposits[_pendingDepositId]; } _pendingDepositId = 0; } /* * Token Account Collection */ function onTokenWalletDeploy(address ownerAddress) public { optional(TipAccount) opt = tokenAccounts.fetch(msg.sender); require(opt.hasValue(), ERROR_INVALID_ROOT_CALLER); TipAccount acc = opt.get(); acc.addr = ownerAddress; tokenAccounts[msg.sender] = acc; _ownerAddress.transfer(0, false, 64); } function _createTokenAccount() private { uint256 owner = address(this).value; tokenAccounts[_tokenRoot] = TipAccount(address(0), owner, uint32(now), 0); ITokenRoot(_tokenRoot).deployEmptyWallet{value: 2 ton, flag: 1, bounce: true} (tvm.functionId(onTokenWalletDeploy), 0, 0, owner, 1 ton); } /* * Get Methods */ function getDeposits() public view returns (mapping (uint32 => Deposit) allDeposits) { allDeposits = deposits; } function getTokenAccounts() external view returns (mapping (address => TipAccount) allAccounts) { allAccounts = tokenAccounts; } function getVoteInfo() external view returns (uint32 reqVotes, uint32 totalVotes, uint32 lockedVotes) { reqVotes = _requestedVotes; totalVotes = _totalVotes; lockedVotes = _lockedVotes; } function getAddresses() public view returns (address ownerAddress) { ownerAddress = _ownerAddress; } function getActiveProposals() public view returns (mapping(address => uint32) activeProposals) { activeProposals = _activeProposals; } }
predefined TokenId for Crystals currency
uint256 _crystalsID = 0;
950,609
[ 1, 1484, 2178, 3155, 548, 364, 14998, 1094, 1031, 5462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 389, 3353, 1094, 1031, 734, 273, 374, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.8.4 <0.9.0; pragma abicoder v2; import '../libraries/RegistryUser.sol'; import '../libraries/Bytes.sol'; import '../interfaces/IRNGConsumer.sol'; /** * Random Number Generator * Name: RNG * Domain: Infrastructure */ contract RNG is RegistryUser { // Use bytes lib for bytes using Bytes for bytes; // Commit scheme data struct CommitSchemeData { uint256 index; bytes32 digest; bytes32 secret; } // Commit scheme progess struct CommitSchemeProgress { uint256 remaining; uint256 total; } // Total committed digest uint256 private totalDigest; uint256 private remainingDigest; // Secret digests map mapping(uint256 => bytes32) private secretDigests; // Reverted digiest map mapping(bytes32 => uint256) private digestIndexs; // Secret storage mapping(uint256 => bytes32) private secretValues; // Commit event event Committed(uint256 indexed index, bytes32 indexed digest); // Reveal event event Revealed(uint256 indexed index, uint256 indexed s, uint256 indexed t); // Pass constructor parameter to User constructor(address registry_, bytes32 domain_) { _registryUserInit(registry_, domain_); } /******************************************************* * Oracle section ********************************************************/ // DKDAO Oracle will commit H(S||t) to blockchain function commit(bytes32 digest) external onlyAllowSameDomain('Oracle') returns (uint256) { return _commit(digest); } // Allow Oracle to commit multiple values to blockchain function batchCommit(bytes calldata digest) external onlyAllowSameDomain('Oracle') returns (bool) { bytes32[] memory digestList = digest.toBytes32Array(); for (uint256 i = 0; i < digestList.length; i += 1) { require(_commit(digestList[i]) > 0, 'RNG: Unable to add digest to blockchain'); } return true; } // DKDAO Oracle will reveal S and t function reveal(bytes memory data) external onlyAllowSameDomain('Oracle') returns (uint256) { require(data.length >= 84, 'RNG: Input data has wrong format'); address target = data.readAddress(0); uint256 index = data.readUint256(20); uint256 secret = data.readUint256(52); uint256 s; uint256 t; remainingDigest -= 1; t = secret & 0xffffffffffffffff; s = secret >> 64; // Make sure that this secret is valid require(secretValues[index] == bytes32(''), 'Rng: This secret was revealed'); require(keccak256(abi.encodePacked(secret)) == secretDigests[index], "Rng: Secret doesn't match digest"); secretValues[index] = bytes32(secret); // Increase last reveal value // Hook call to fair distribution if (target != address(0x00)) { require( IRNGConsumer(target).compute(data.readBytes(52, data.length - 52)), "RNG: Can't do callback to distributor" ); } emit Revealed(index, s, t); return index; } /******************************************************* * Private section ********************************************************/ // Commit digest to blockchain state function _commit(bytes32 digest) private returns (uint256) { // We begin from 1 instead of 0 to prevent error totalDigest += 1; remainingDigest += 1; secretDigests[totalDigest] = digest; digestIndexs[digest] = totalDigest; emit Committed(totalDigest, digest); return totalDigest; } /******************************************************* * View section ********************************************************/ // Get progress of commit scheme function getDataByIndex(uint256 index) external view returns (CommitSchemeData memory) { return CommitSchemeData({ index: index, digest: secretDigests[index], secret: secretValues[index] }); } // Get progress of commit scheme function getDataByDigest(bytes32 digest) external view returns (CommitSchemeData memory) { uint256 index = digestIndexs[digest]; return CommitSchemeData({ index: index, digest: secretDigests[index], secret: secretValues[index] }); } // Get progress of commit scheme function getProgress() external view returns (CommitSchemeProgress memory) { return CommitSchemeProgress({ remaining: remainingDigest, total: totalDigest }); } }
Total committed digest
uint256 private totalDigest;
12,964,118
[ 1, 5269, 16015, 5403, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 2254, 5034, 3238, 2078, 9568, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x675D7ee2B31E4B47C0D3F3E7FdAcF7Dede4904FF/sources/contracts/DarwinLiquidityBundles.sol
@notice Enter a Bundle @dev This functions takes an amount of ETH from a user and pairs it with a X amount of _token (already present in the contract), and locks it for a year. After the lock ends, the user will be able to not only withdraw the ETH he provided, but also the respective token amount. @param _token The bundle token address @param _desiredTokenAmount The amount of the token to pair ETH with refund dust ETH, if any
function enterBundle( address _token, uint _desiredTokenAmount ) external payable { (uint tokenAmount, uint priceInWeth) = tokenInfo(_token); if (_desiredTokenAmount > tokenAmount) { _desiredTokenAmount = tokenAmount; } uint256 ethValue = (_desiredTokenAmount * priceInWeth) / (10 ** IERC20(_token).decimals()); require(msg.value >= ethValue, "DarwinLiquidityBundles: INSUFFICIENT_ETH"); if (ethValue == 0) { ethValue = msg.value; } IERC20(_token).approve(address(darwinRouter), _desiredTokenAmount); _token, _desiredTokenAmount, 0, 0, address(this), block.timestamp + 600 ); User storage user = userInfo[msg.sender][_token]; totalLpAmount[_token] += liquidity; user.lpAmount += liquidity; user.lockEnd = block.timestamp + LOCK_PERIOD; user.bundledEth += amountETH; user.bundledToken += amountToken; if (msg.value > amountETH) { require(success, "DarwinLiquidityBundles: ETH_TRANSFER_FAILED"); } if (address(masterChef) != address(0)) { address pair = darwinFactory.getPair(_token, WETH); if (masterChef.poolExistence(IERC20(pair))) { IERC20(pair).approve(address(masterChef), liquidity); masterChef.depositByLPToken(IERC20(pair), liquidity, false, 0); user.inMasterchef = true; } } emit EnterBundle(msg.sender, amountToken, amountETH, block.timestamp, block.timestamp + LOCK_PERIOD); }
8,288,867
[ 1, 10237, 279, 8539, 225, 1220, 4186, 5530, 392, 3844, 434, 512, 2455, 628, 279, 729, 471, 5574, 518, 598, 279, 1139, 3844, 434, 389, 2316, 261, 17583, 3430, 316, 326, 6835, 3631, 471, 13046, 518, 364, 279, 3286, 18, 7360, 326, 2176, 3930, 16, 326, 729, 903, 506, 7752, 358, 486, 1338, 598, 9446, 326, 512, 2455, 3904, 2112, 16, 1496, 2546, 326, 17613, 1147, 3844, 18, 225, 389, 2316, 1021, 3440, 1147, 1758, 225, 389, 30458, 1345, 6275, 1021, 3844, 434, 326, 1147, 358, 3082, 512, 2455, 598, 16255, 302, 641, 512, 2455, 16, 309, 1281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6103, 3405, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 2254, 389, 30458, 1345, 6275, 203, 565, 262, 3903, 8843, 429, 288, 203, 3639, 261, 11890, 1147, 6275, 16, 2254, 6205, 382, 59, 546, 13, 273, 1147, 966, 24899, 2316, 1769, 203, 3639, 309, 261, 67, 30458, 1345, 6275, 405, 1147, 6275, 13, 288, 203, 5411, 389, 30458, 1345, 6275, 273, 1147, 6275, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 13750, 620, 273, 261, 67, 30458, 1345, 6275, 380, 6205, 382, 59, 546, 13, 342, 261, 2163, 2826, 467, 654, 39, 3462, 24899, 2316, 2934, 31734, 10663, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 13750, 620, 16, 315, 40, 19992, 48, 18988, 24237, 16151, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 1584, 44, 8863, 203, 3639, 309, 261, 546, 620, 422, 374, 13, 288, 203, 5411, 13750, 620, 273, 1234, 18, 1132, 31, 203, 3639, 289, 203, 203, 3639, 467, 654, 39, 3462, 24899, 2316, 2934, 12908, 537, 12, 2867, 12, 28076, 8259, 3631, 389, 30458, 1345, 6275, 1769, 203, 5411, 389, 2316, 16, 203, 5411, 389, 30458, 1345, 6275, 16, 203, 5411, 374, 16, 203, 5411, 374, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 397, 14707, 203, 3639, 11272, 203, 203, 3639, 2177, 2502, 729, 273, 16753, 63, 3576, 18, 15330, 6362, 67, 2316, 15533, 203, 203, 3639, 2078, 48, 84, 6275, 63, 67, 2316, 65, 1011, 4501, 372, 24237, 31, 203, 3639, 729, 18, 9953, 6275, 1011, 4501, 372, 24237, 2 ]
./full_match/1/0xdF9F1f1E6f4107f05dBb425a5f72b5366C8bAc00/sources/durdeninu.sol
@notice Withdraws the ether distributed to the sender. @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal virtual returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add( _withdrawableDividend ); emit DividendWithdrawn(user, _withdrawableDividend); (bool success, ) = user.call{ value: _withdrawableDividend, gas: 3000 }(""); if (!success) { withdrawnDividends[user] = withdrawnDividends[user].sub( _withdrawableDividend ); return 0; } return _withdrawableDividend; } return 0; }
2,928,164
[ 1, 1190, 9446, 87, 326, 225, 2437, 16859, 358, 326, 5793, 18, 225, 2597, 24169, 279, 1375, 7244, 26746, 1190, 9446, 82, 68, 871, 309, 326, 3844, 434, 598, 9446, 82, 225, 2437, 353, 6802, 2353, 374, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1918, 9446, 7244, 26746, 951, 1299, 12, 2867, 8843, 429, 729, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 389, 1918, 9446, 429, 7244, 26746, 273, 598, 9446, 429, 7244, 26746, 951, 12, 1355, 1769, 203, 3639, 309, 261, 67, 1918, 9446, 429, 7244, 26746, 405, 374, 13, 288, 203, 5411, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 65, 273, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 8009, 1289, 12, 203, 7734, 389, 1918, 9446, 429, 7244, 26746, 203, 5411, 11272, 203, 5411, 3626, 21411, 26746, 1190, 9446, 82, 12, 1355, 16, 389, 1918, 9446, 429, 7244, 26746, 1769, 203, 5411, 261, 6430, 2216, 16, 262, 273, 729, 18, 1991, 95, 203, 7734, 460, 30, 389, 1918, 9446, 429, 7244, 26746, 16, 203, 7734, 16189, 30, 29839, 203, 5411, 289, 2932, 8863, 203, 203, 5411, 309, 16051, 4768, 13, 288, 203, 7734, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 65, 273, 598, 9446, 82, 7244, 350, 5839, 63, 1355, 8009, 1717, 12, 203, 10792, 389, 1918, 9446, 429, 7244, 26746, 203, 7734, 11272, 203, 7734, 327, 374, 31, 203, 5411, 289, 203, 203, 5411, 327, 389, 1918, 9446, 429, 7244, 26746, 31, 203, 3639, 289, 203, 203, 3639, 327, 374, 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 ]
// SPDX-License-Identifier: Apache License, Version 2.0 pragma solidity 0.8.0; import "./ERC20Burnable.sol"; import "./ERC20Pausable.sol"; import "./Ownable.sol"; /** * @dev {ERC20} token implementing the {IERC20} interface, including: * * - Preminted initial supply of 3.25 Billion tokens allocated to owner * - Ability for holders to transfer their tokens * - Ability for holders to burn (destroy) their tokens * - Ability for owner to pause/stop all token transfers * * This contract uses {ERC20Pausable} for pausing token transfers which is useful * for scenarios such as preventing trades until the end of an evaluation period, * or having an emergency switch for freezing all token transfers in the event of * a large bug or an exchange hack. * * The account that deploys the contract will be granted the allocation of the * preminted initial supply along with the owner role which allows it to pause * token transfers. * * This contract uses {ERC20Burnable} to allow token holders to destroy (burn), * both their own tokens and those that they have an allowance for, in a way * that can be recognized off-chain (via event analysis). * * The inherited ERC20 contract includes the OpenZeppelin non-standard * {decreaseAllowance} and {increaseAllowance} functions as alternatives to the * standard {approve} function. * * The inherited contracts follows 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. */ contract DrifeToken is ERC20Burnable, ERC20Pausable, Ownable { /** * @dev Mints an initial supply of 3.25 Billion DRF tokens with 18 decimals and * transfers them to deploying address which is also made the contract `owner`. * * See {ERC20-constructor}. */ constructor() ERC20("Drife", "DRF") { _mint(_msgSender(), 3.25 * 10**9 * 10**18); } /** * @dev Toggles between paused <-> unpaused states to disallow <-> allow * token transfers. * * See {ERC20Pausable} - {Pausable-paused()}, {Pausable-_pause()} and * {Pausable-_unpause()}. * * Requirements: * * - the caller must have `owner` priviledges. */ function togglePause() public onlyOwner { paused() ? _unpause() : _pause(); } /** * @dev Overridden hook that is called before any transfer of tokens, * including minting and burning. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
* @dev {ERC20} token implementing the {IERC20} interface, including: - Preminted initial supply of 3.25 Billion tokens allocated to owner - Ability for holders to transfer their tokens - Ability for holders to burn (destroy) their tokens - Ability for owner to pause/stop all token transfers This contract uses {ERC20Pausable} for pausing token transfers which is useful for scenarios such as preventing trades until the end of an evaluation period, or having an emergency switch for freezing all token transfers in the event of a large bug or an exchange hack. The account that deploys the contract will be granted the allocation of the preminted initial supply along with the owner role which allows it to pause token transfers. This contract uses {ERC20Burnable} to allow token holders to destroy (burn), both their own tokens and those that they have an allowance for, in a way that can be recognized off-chain (via event analysis). The inherited ERC20 contract includes the OpenZeppelin non-standard {decreaseAllowance} and {increaseAllowance} functions as alternatives to the standard {approve} function. The inherited contracts follows 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./
contract DrifeToken is ERC20Burnable, ERC20Pausable, Ownable { pragma solidity 0.8.0; constructor() ERC20("Drife", "DRF") { _mint(_msgSender(), 3.25 * 10**9 * 10**18); } function togglePause() public onlyOwner { paused() ? _unpause() : _pause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
13,866,908
[ 1, 95, 654, 39, 3462, 97, 1147, 19981, 326, 288, 45, 654, 39, 3462, 97, 1560, 16, 6508, 30, 225, 300, 453, 2764, 474, 329, 2172, 14467, 434, 890, 18, 2947, 605, 737, 285, 2430, 11977, 358, 3410, 225, 300, 9771, 1889, 364, 366, 4665, 358, 7412, 3675, 2430, 225, 300, 9771, 1889, 364, 366, 4665, 358, 18305, 261, 11662, 13, 3675, 2430, 225, 300, 9771, 1889, 364, 3410, 358, 11722, 19, 5681, 777, 1147, 29375, 1220, 6835, 4692, 288, 654, 39, 3462, 16507, 16665, 97, 364, 6790, 9940, 1147, 29375, 1492, 353, 5301, 364, 22456, 4123, 487, 5309, 310, 1284, 5489, 3180, 326, 679, 434, 392, 9873, 3879, 16, 578, 7999, 392, 801, 24530, 1620, 364, 4843, 94, 310, 777, 1147, 29375, 316, 326, 871, 434, 279, 7876, 7934, 578, 392, 7829, 11769, 18, 1021, 2236, 716, 5993, 383, 1900, 326, 6835, 903, 506, 17578, 326, 13481, 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, 16351, 11473, 24723, 1345, 353, 4232, 39, 3462, 38, 321, 429, 16, 4232, 39, 3462, 16507, 16665, 16, 14223, 6914, 288, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 20, 31, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 8956, 24723, 3113, 315, 6331, 42, 7923, 288, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 890, 18, 2947, 380, 1728, 636, 29, 380, 1728, 636, 2643, 1769, 203, 565, 289, 203, 203, 565, 445, 10486, 19205, 1435, 1071, 1338, 5541, 288, 203, 3639, 17781, 1435, 692, 389, 318, 19476, 1435, 294, 389, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 3849, 12, 654, 39, 3462, 16, 4232, 39, 3462, 16507, 16665, 13, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Copyright 2019 Monerium ehf. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol"; /** * @title SimpleToken * @dev This simple [ERC20] compatible token is used in the test suite. */ contract SimpleToken is BasicToken { constructor() public { totalSupply_ = 10000000; balances[msg.sender] = totalSupply_; } }
* @title SimpleToken @dev This simple [ERC20] compatible token is used in the test suite./
contract SimpleToken is BasicToken { constructor() public { totalSupply_ = 10000000; balances[msg.sender] = totalSupply_; } }
14,018,308
[ 1, 5784, 1345, 225, 1220, 4143, 306, 654, 39, 3462, 65, 7318, 1147, 353, 1399, 316, 326, 1842, 11371, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4477, 1345, 353, 7651, 1345, 288, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 2078, 3088, 1283, 67, 273, 2130, 11706, 31, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 67, 31, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xF5a08C5F44a52bA220190239d7596a2679447981/sources/browser/TILYgo.sol
ETH Includes Affiliate commissions
uint totalEarnings;
8,173,159
[ 1, 1584, 44, 657, 8993, 23906, 330, 3840, 1543, 1054, 1115, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2254, 2078, 41, 1303, 899, 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.15; contract ERC223Interface { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); function transfer(address to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value, bytes data); } /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data){ TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } function rewiewToken () returns (address, uint, bytes, bytes4) { TKN memory tkn; return (tkn.sender, tkn.value, tkn.data, tkn.sig); } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * @title ERC223 standard token implementation. */ contract FNCTToken is ERC223Interface, SafeMath { mapping(address => uint) balances; // List of user balances. address public owner; string public name = "Finecs Token"; string public symbol = "FNC"; uint8 public decimals = 18; uint public totalSupply = 500000000 * (10 ** uint(decimals));//Crowdsale supply uint public poolReserve = 30000000 * (10 ** uint(decimals));//Reserve pool uint public poolTeam = 30000000 * (10 ** uint(decimals));//Team pool uint public poolBounty = 30000000 * (10 ** uint(decimals));//Bounty pool uint public poolAdvisors = 30000000 * (10 ** uint(decimals));//Advisors pool uint public poolSale = 180000000 * (10 ** uint(decimals));//Sale pool uint public sellPrice = 1000000000000000 wei;//Tokens are sold for this manual price, rather than predefined price. function FNCTToken () { bytes memory empty; owner = msg.sender; //Add reserved pool tokens to the owner address balances[owner] = safeAdd(balances[owner], totalSupply); Transfer(0, this, totalSupply, empty); Transfer(this, owner, totalSupply, empty); } /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes _data) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to], _value); if(codeLength>0) { ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn&#39;t contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint _value) { uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to], _value); if(codeLength>0) { ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value, empty); } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } }
Add reserved pool tokens to the owner address
function FNCTToken () { bytes memory empty; owner = msg.sender; balances[owner] = safeAdd(balances[owner], totalSupply); Transfer(0, this, totalSupply, empty); Transfer(this, owner, totalSupply, empty); }
7,725,782
[ 1, 986, 8735, 2845, 2430, 358, 326, 3410, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 27103, 1268, 1345, 1832, 288, 203, 3639, 1731, 3778, 1008, 31, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 8443, 65, 273, 4183, 986, 12, 70, 26488, 63, 8443, 6487, 2078, 3088, 1283, 1769, 203, 3639, 12279, 12, 20, 16, 333, 16, 2078, 3088, 1283, 16, 1008, 1769, 203, 3639, 12279, 12, 2211, 16, 3410, 16, 2078, 3088, 1283, 16, 1008, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./SafeMath.sol"; import "./IERC20.sol"; import "./MagicLampERC721.sol"; interface SuperMagic { function compose(address owner) external returns (bool); function bet(address owner) external returns (bool); } /** * @title MagicLamps NFT contract * @dev Extends MagicLampERC721 Non-Fungible Token Standard basic implementation */ contract MagicLamps is MagicLampERC721 { using SafeMath for uint256; using Address for address; // Public variables address public superMagicContract; // This is SHA256 hash of the provenance record of all MagicLamp artworks // It is derived by hashing every individual NFT's picture, and then concatenating all those hash, deriving yet another SHA256 from that. string public MAGICLAMPS_PROVENANCE = ""; uint256 public constant SALE_START_TIMESTAMP = 1631372400; uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (7 days); uint256 public constant MAX_MAGICLAMP_SUPPLY = 10000; uint256 public MAGICLAMP_MINT_COUNT_LIMIT = 30; uint256 public constant REFERRAL_REWARD_PERCENT = 1000; // 10% uint256 public constant LIQUIDITY_FUND_PERCENT = 1000; // 10% bool public saleIsActive = false; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public mintPrice = 30000000000000000; // 0.03 ETH uint256 public aldnReward = 10000000000000000000; // (10% of ALDN totalSupply) / 10000 // Mapping from token ID to puzzle mapping (uint256 => uint256) public puzzles; // Referral management uint256 public totalReferralRewardAmount; uint256 public distributedReferralRewardAmount; mapping(address => uint256) public referralRewards; mapping(address => mapping(address => bool)) public referralStatus; address public liquidityFundAddress = 0x9C73aAdcFb1ee7314d2Ac96150073F88b47E0A32; address public devAddress = 0xB689bA113effd47d38CfF88A682465945bd80829; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 == 0x93254542 * => 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; // Events event DistributeReferralRewards(uint256 indexed magicLampIndex, uint256 amount); event EarnReferralReward(address indexed account, uint256 amount); event WithdrawFund(uint256 liquidityFund, uint256 treasuryFund); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_, address aladdin, address genie) MagicLampERC721(name_, symbol_) { aladdinToken = aladdin; genieToken = genie; // register the supported interfaces to conform to MagiclampsERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function mintMagicLamp(uint256 count, address referrer) public payable { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(saleIsActive, "Sale must be active to mint"); require(totalSupply() < MAX_MAGICLAMP_SUPPLY, "Sale has already ended"); require(count > 0, "count cannot be 0"); require(count <= MAGICLAMP_MINT_COUNT_LIMIT, "Exceeds mint count limit"); require(totalSupply().add(count) <= MAX_MAGICLAMP_SUPPLY, "Exceeds max supply"); if(msg.sender != owner()) { require(mintPrice.mul(count) <= msg.value, "Ether value sent is not correct"); } IERC20(aladdinToken).transfer(_msgSender(), aldnReward.mul(count)); for (uint256 i = 0; i < count; i++) { uint256 mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } puzzles[mintIndex] = getRandomNumber(type(uint256).min, type(uint256).max.sub(1)); _safeMint(_msgSender(), mintIndex); } if (referrer != address(0) && referrer != _msgSender()) { _rewardReferral(referrer, _msgSender(), msg.value); } /** * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense */ if (startingIndexBlock == 0 && (totalSupply() == MAX_MAGICLAMP_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function setSuperMagicContractAddress(address contractAddress) public onlyOwner { superMagicContract = contractAddress; } /** * Set price to mint a MagicLamps. */ function setMintPrice(uint256 _price) external onlyOwner { mintPrice = _price; } /** * Set maximum count to mint per once. */ function setMintCountLimit(uint256 count) external onlyOwner { MAGICLAMP_MINT_COUNT_LIMIT = count; } function setDevAddress(address _devAddress) external onlyOwner { devAddress = _devAddress; } /** * Set ALDN reward amount to mint a MagicLamp. */ function setALDNReward(uint256 _aldnReward) external onlyOwner { aldnReward = _aldnReward; } /** * Mint MagicLamps by owner */ function reserveMagicLamps(address to, uint256 count) external onlyOwner { require(to != address(0), "Invalid address to reserve."); uint256 supply = totalSupply(); uint256 i; for (i = 0; i < count; i++) { _safeMint(to, supply + i); } if (startingIndexBlock == 0) { startingIndexBlock = block.number; } } function bet(uint256 useTokenId1) public { require(superMagicContract != address(0), "SuperMagic contract address need be set"); address from = msg.sender; require(ownerOf(useTokenId1) == from, "ERC721: use of token1 that is not own"); // _burn(useTokenId1); safeTransferFrom(from, superMagicContract, useTokenId1); SuperMagic superMagic = SuperMagic(superMagicContract); bool result = superMagic.bet(from); require(result, "SuperMagic compose failed"); } function compose(uint256 useTokenId1, uint256 useTokenId2, uint256 useTokenId3) public { require(superMagicContract != address(0), "SuperMagic contract address need be set"); address from = msg.sender; require(ownerOf(useTokenId1) == from, "ERC721: use of token1 that is not own"); require(ownerOf(useTokenId2) == from, "ERC721: use of token2 that is not own"); require(ownerOf(useTokenId3) == from, "ERC721: use of token3 that is not own"); // _burn(useTokenId1); // _burn(useTokenId2); // _burn(useTokenId3); safeTransferFrom(from, superMagicContract, useTokenId1); safeTransferFrom(from, superMagicContract, useTokenId2); safeTransferFrom(from, superMagicContract, useTokenId3); SuperMagic superMagic = SuperMagic(superMagicContract); bool result = superMagic.compose(from); require(result, "SuperMagic compose failed"); } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory _provenanceHash) external onlyOwner { MAGICLAMPS_PROVENANCE = _provenanceHash; } /* * Pause sale if active, make active if paused */ function setSaleState() external onlyOwner { saleIsActive = !saleIsActive; } /** * @dev Finalize starting index */ function finalizeStartingIndex() public virtual { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_MAGICLAMP_SUPPLY; // 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_MAGICLAMP_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * @dev Withdraws liquidity and treasury fund. */ function withdrawFund() public onlyOwner { uint256 fund = address(this).balance.sub(totalReferralRewardAmount).add(distributedReferralRewardAmount); uint256 liquidityFund = _percent(fund, LIQUIDITY_FUND_PERCENT); payable(liquidityFundAddress).transfer(liquidityFund); uint256 treasuryFund = fund.sub(liquidityFund); uint256 devFund = treasuryFund.mul(30).div(100); payable(devAddress).transfer(devFund); payable(msg.sender).transfer(treasuryFund.sub(devFund)); emit WithdrawFund(liquidityFund, treasuryFund); } /** * @dev Withdraws ALDN to treasury if ALDN after sale ended */ function withdrawFreeToken(address token) public onlyOwner { if (token == aladdinToken) { require(totalSupply() >= MAX_MAGICLAMP_SUPPLY, "Sale has not ended"); } IERC20(token).transfer(msg.sender, IERC20(token).balanceOf(address(this))); } function _rewardReferral(address referrer, address referee, uint256 referralAmount) internal { uint256 referrerBalance = MagicLampERC721.balanceOf(referrer); bool status = referralStatus[referrer][referee]; uint256 rewardAmount = _percent(referralAmount, REFERRAL_REWARD_PERCENT); if (referrerBalance != 0 && rewardAmount != 0 && !status) { referralRewards[referrer] = referralRewards[referrer].add(rewardAmount); totalReferralRewardAmount = totalReferralRewardAmount.add(rewardAmount); emit EarnReferralReward(referrer, rewardAmount); referralRewards[referee] = referralRewards[referee].add(rewardAmount); totalReferralRewardAmount = totalReferralRewardAmount.add(rewardAmount); emit EarnReferralReward(referee, rewardAmount); referralStatus[referrer][referee] = true; } } function distributeReferralRewards(uint256 startMagicLampId, uint256 endMagicLampId) external onlyOwner { require(block.timestamp > SALE_START_TIMESTAMP, "Sale has not started"); require(startMagicLampId < totalSupply(), "Index is out of range"); if (endMagicLampId >= totalSupply()) { endMagicLampId = totalSupply().sub(1); } for (uint256 i = startMagicLampId; i <= endMagicLampId; i++) { address owner = ownerOf(i); uint256 amount = referralRewards[owner]; if (amount > 0) { magicLampWallet.depositETH{ value: amount }(address(this), i, amount); distributedReferralRewardAmount = distributedReferralRewardAmount.add(amount); delete referralRewards[owner]; emit DistributeReferralRewards(i, amount); } } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() external onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } function emergencyWithdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /** * Get the array of token for owner. */ function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); for (uint256 index; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 custom add */ function burn(uint256 burnQuantity) 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 "./SafeMath.sol"; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./ERC165.sol"; import "./Strings.sol"; import "./Ownable.sol"; import "./EnumerableMap.sol"; import "./EnumerableSet.sol"; import "./IMagicLampERC721.sol"; import "./Stringstrings.sol"; import "./IERC20.sol"; import "./SafeERC20.sol"; interface IMagicLampWallet { function depositETH(address host, uint256 id, uint256 amount) external payable; function withdrawAll(address host, uint256 id) external; } /** * @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 MagicLampERC721 is ERC165, IERC721, IERC721Metadata, IMagicLampERC721, Ownable { using SafeMath for uint256; using Address for address; using Strings for uint256; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Stringstrings for string; using SafeERC20 for IERC20; // Token name string private _name; // Token symbol string private _symbol; // Token URI string private _tokenUri; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap internal _tokenOwners; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) internal _holderTokens; // Mapping from token ID to approved address mapping (uint256 => address) internal _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal _operatorApprovals; uint256 public constant NAME_CHANGE_PRICE = 1337 * (10**18); // Mapping from token ID to name mapping (uint256 => string) internal _tokenName; // Mapping if certain name string has already been reserved mapping (string => bool) internal _nameReserved; // Mapping from token ID to whether the MagicLamp was minted before reveal mapping (uint256 => bool) internal _mintedBeforeReveal; address public aladdinToken; address public genieToken; IMagicLampWallet public magicLampWallet; // Intializing the random nonce uint256 private _randNonce = 0; // Events event NameChange(uint256 indexed magicLampIndex, string newName); /** * @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), "MagicLampERC721: 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, "MagicLampERC721: 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 baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return _tokenUri; } // Set Token URI function setBaseURI(string memory url) public onlyOwner { _tokenUri = url; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = MagicLampERC721.ownerOf(tokenId); require(to != owner, "MagicLampERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "MagicLampERC721: 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), "MagicLampERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "MagicLampERC721: 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), "MagicLampERC721: 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), "MagicLampERC721: 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 MagicLampERC721 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), "MagicLampERC721: 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) public 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), "MagicLampERC721: operator query for nonexistent token"); address owner = MagicLampERC721.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), "MagicLampERC721: 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), "MagicLampERC721: mint to the zero address"); require(!exists(tokenId), "MagicLampERC721: 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 = MagicLampERC721.ownerOf(tokenId); // Prevent burner's MagicLampWallet assets to be transferred together magicLampWallet.withdrawAll(address(this), tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), 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(MagicLampERC721.ownerOf(tokenId) == from, "MagicLampERC721: transfer of token that is not own"); require(to != address(0), "MagicLampERC721: 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 Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(MagicLampERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("MagicLampERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override virtual returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override virtual 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 virtual returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Returns name of the MagicLamp at index. */ function tokenNameByIndex(uint256 index) public view virtual returns (string memory) { return _tokenName[index]; } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view virtual returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns if the MagicLamp has been minted before reveal phase */ function isMintedBeforeReveal(uint256 index) public view override virtual returns (bool) { return _mintedBeforeReveal[index]; } function initMagicLampWalletAddress(address newMagicLampWallet) public virtual onlyOwner { magicLampWallet = IMagicLampWallet(newMagicLampWallet); } /** * @dev Changes the name of MagicLamp of given tokenId */ function changeName(uint256 tokenId, string memory newName) public virtual { require(_msgSender() == ownerOf(tokenId), "Caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(sha256(bytes(toLower(newName))) == sha256(bytes(toLower(_tokenName[tokenId]))) || isNameReserved(newName) == false, "Name already reserved"); IERC20(genieToken).safeTransferFrom(_msgSender(), address(this), NAME_CHANGE_PRICE); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { _toggleReserveName(_tokenName[tokenId], false); } _toggleReserveName(newName, true); _tokenName[tokenId] = newName; IERC20(genieToken).burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function _toggleReserveName(string memory str, bool isReserve) internal virtual { _nameReserved[toLower(str)] = isReserve; } /** * @dev Checks if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure virtual returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure virtual returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /** * @dev Counts percentage of amount */ function _percent(uint256 amount, uint256 fraction) internal pure virtual returns(uint256) { return amount.mul(fraction).div(10000); } function getRandomNumber(uint256 a, uint256 b) internal virtual returns (uint256) { uint256 min = a; uint256 max = (b.add(1)).sub(min); _randNonce ++; return (uint256(uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, _randNonce)))%max)).add(min); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; address private _authorizedNewOwner; event OwnershipTransferAuthorization(address indexed authorizedAddress); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Returns the address of the current authorized new owner. */ function authorizedNewOwner() public view virtual returns (address) { return _authorizedNewOwner; } /** * @notice Authorizes the transfer of ownership from _owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner { _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner. */ function assumeOwnership() external { require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership"); emit OwnershipTransferred(_owner, _authorizedNewOwner); _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); } /** * @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. * * @param confirmAddress The address wants to give up ownership. */ function renounceOwnership(address confirmAddress) public virtual onlyOwner { require(confirmAddress == _owner, "Ownable: confirm address is wrong"); emit OwnershipTransferred(_owner, address(0)); _authorizedNewOwner = address(0); _owner = address(0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./EnumerableSet.sol"; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping (bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @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) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, 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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Enumerable.sol"; interface IMagicLampERC721 is IERC721Enumerable { function isMintedBeforeReveal(uint256 index) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Stringstrings { function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k -1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function fromAddress(address addr) internal pure returns(string memory) { bytes20 addrBytes = bytes20(addr); bytes16 hexAlphabet = "0123456789abcdef"; bytes memory result = new bytes(42); result[0] = '0'; result[1] = 'x'; for (uint i = 0; i < 20; i++) { result[i * 2 + 2] = hexAlphabet[uint8(addrBytes[i] >> 4)]; result[i * 2 + 3] = hexAlphabet[uint8(addrBytes[i] & 0x0f)]; } return string(result); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 See {IERC721-ownerOf}./
function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "MagicLampERC721: owner query for nonexistent token"); }
6,846,951
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 8443, 951, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 2316, 5460, 414, 18, 588, 12, 2316, 548, 16, 315, 19289, 48, 931, 654, 39, 27, 5340, 30, 3410, 843, 364, 1661, 19041, 1147, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xb9Bd0D26604357d6643801b30158A726a3F52a47/sources/_thirdweb-dev/contracts/base/Staking721Base.sol
@dev Admin can withdraw excess reward tokens.
function withdrawRewardTokens(uint256 _amount) external nonReentrant { }
1,961,976
[ 1, 4446, 848, 598, 9446, 23183, 19890, 2430, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 17631, 1060, 5157, 12, 11890, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-22 */ // SPDX-License-Identifier: MIT // Author: 0xTycoon // Repo: github.com/0xTycoon/punksceo pragma solidity ^0.8.11; //import "./safemath.sol"; // don't need since v0.8 //import "./ceo.sol"; /* PUNKS CEO (and "Cigarette" token) WEB: https://punksceo.eth.limo / https://punksceo.eth.link IPFS: See content hash record for punksceo.eth Token Address: cigtoken.eth There is NO trade tax or any other fee in the standard ERC20 methods of this token. The "CEO of CryptoPunks" game element is optional and implemented for your entertainment. ### THE RULES OF THE GAME 1. Anybody can buy the CEO title at any time using Cigarettes. (The CEO of all cryptopunks) 2. When buying the CEO title, you must nominate a punk, set the price and pre-pay the tax. 3. The CEO title can be bought from the existing CEO at any time. 4. To remain a CEO, a daily tax needs to be paid. 5. The tax is 0.1% of the price to buy the CEO title, to be charged per epoch. 6. The CEO can be removed if they fail to pay the tax. A reward of CIGs is paid to the whistleblower. 7. After Removing a CEO: A dutch auction is held, where the price will decrease 10% every half-an-epoch. 8. The price can be changed by the CEO at any time. (Once per block) 9. An epoch is 7200 blocks. 10. All the Cigarettes from the sale are burned. 11. All tax is burned 12. After buying the CEO title, the old CEO will get their unspent tax deposit refunded ### CEO perk 13. The CEO can increase or decrease the CIG farming block reward by 20% every 2nd epoch! However, note that the issuance can never be more than 1000 CIG per block, also never under 0.0001 CIG. 14. THE CEO gets to hold a NFT in their wallet. There will only be ever 1 this NFT. The purpose of this NFT is so that everyone can see that they are the CEO. IMPORTANT: This NFT will be revoked once the CEO title changes. Also, the NFT cannot be transferred by the owner, the only way to transfer is for someone else to buy the CEO title! (Think of this NFT as similar to a "title belt" in boxing.) END * states * 0 = initial * 1 = CEO reigning * 2 = Dutch auction Notes: It was decided that whoever buys the CEO title does not have to hold a punk and can nominate any punk they wish. This is because some may hold their punks in cold storage, plus checking ownership costs additional gas. Besides, CEOs are usually appointed by the board. Credits: - LP Staking based on code from SushiSwap's MasterChef.sol - ERC20 & SafeMath based on lib from OpenZeppelin */ contract Cig { //using SafeMath for uint256; // no need since Solidity 0.8 // ERC20 stuff string public constant name = "Cigarette Token"; string public constant symbol = "CIG"; uint8 public constant decimals = 18; uint256 public totalSupply = 0; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // UserInfo keeps track of user LP deposits and withdrawals struct UserInfo { uint256 deposit; // How many LP tokens the user has deposited. uint256 rewardDebt; // keeps track of how much reward was paid out } mapping(address => UserInfo) public userInfo; // keeps track of UserInfo for each staking address address public admin; // admin is used for deployment, burned after ILiquidityPoolERC20 public lpToken; // lpToken is the address of LP token contract that's being staked. uint256 public lastRewardBlock; // Last block number that cigarettes distribution occurs. uint256 public accCigPerShare; // Accumulated cigarettes per share, times 1e12. See below. uint256 public cigPerBlock; // CIGs per-block rewarded and split with LPs bytes32 public graffiti; // a 32 character graffiti set when buying a CEO ICryptoPunk public punks; // a reference to the CryptoPunks contract event Deposit(address indexed user, uint256 amount); // when depositing LP tokens to stake, or harvest event Withdraw(address indexed user, uint256 amount); // when withdrawing LP tokens form staking event EmergencyWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed event RewardUp(uint256 reward, uint256 upAmount); // when cigPerBlock is increased event RewardDown(uint256 reward, uint256 downAmount); // when cigPerBlock is decreased event Claim(address indexed owner, uint indexed punkIndex, uint256 value); // when a punk is claimed mapping(uint => bool) public claims; // keep track of claimed punks modifier onlyAdmin { require( msg.sender == admin, "Only admin can call this" ); _; } uint256 constant MIN_PRICE = 1e12; // 0.000001 CIG uint256 constant CLAIM_AMOUNT = 100000 ether; // claim amount for each punk uint256 constant MIN_REWARD = 1e14; // minimum block reward of 0.0001 CIG (1e14 wei) uint256 constant MAX_REWARD = 1000 ether; // maximum block reward of 1000 CIG address public The_CEO; // address of CEO uint public CEO_punk_index; // which punk id the CEO is using uint256 public CEO_price = 50000 ether; // price to buy the CEO title uint256 public CEO_state; // state has 3 states, described above. uint256 public CEO_tax_balance; // deposit to be used to pay the CEO tax uint256 public taxBurnBlock; // The last block when the tax was burned uint256 public rewardsChangedBlock; // which block was the last reward increase / decrease uint256 private immutable CEO_epoch_blocks; // secs per day divided by 12 (86400 / 12), assuming 12 sec blocks uint256 private immutable CEO_auction_blocks; // 3600 blocks event NewCEO(address indexed user, uint indexed punk_id, uint256 new_price, bytes32 graffiti); // when a CEO is bought event TaxDeposit(address indexed user, uint256 amount); // when tax is deposited event RevenueBurned(address indexed user, uint256 amount); // when tax is burned event TaxBurned(address indexed user, uint256 amount); // when tax is burned event CEODefaulted(address indexed called_by, uint256 reward); // when CEO defaulted on tax event CEOPriceChange(uint256 price); // when CEO changed price modifier onlyCEO { require( msg.sender == The_CEO, "only CEO can call this" ); _; } IRouterV2 private immutable V2ROUTER; // address of router used to get the price quote ICEOERC721 private immutable The_NFT; // reference to the CEO NFT token address private immutable MASTERCHEF_V2; // address pointing to SushiSwap's MasterChefv2 contract /** * @dev constructor * @param _startBlock starting block when rewards start * @param _cigPerBlock Number of CIG tokens rewarded per block * @param _punks address of the cryptopunks contract * @param _CEO_epoch_blocks how many blocks between each epochs * @param _CEO_auction_blocks how many blocks between each auction discount * @param _CEO_price starting price to become CEO (in CIG) * @param _MASTERCHEF_V2 address of the MasterChefv2 contract */ constructor( uint256 _startBlock, uint256 _cigPerBlock, address _punks, uint _CEO_epoch_blocks, uint _CEO_auction_blocks, uint256 _CEO_price, address _MASTERCHEF_V2, bytes32 _graffiti, address _NFT, address _V2ROUTER ) { lastRewardBlock = _startBlock; cigPerBlock = _cigPerBlock; admin = msg.sender; // the admin key will be burned after deployment punks = ICryptoPunk(_punks); CEO_epoch_blocks = _CEO_epoch_blocks; CEO_auction_blocks = _CEO_auction_blocks; CEO_price = _CEO_price; MASTERCHEF_V2 = _MASTERCHEF_V2; graffiti = _graffiti; The_NFT = ICEOERC721(_NFT); V2ROUTER = IRouterV2(_V2ROUTER); // mint the tokens for the airdrop and place them in the CryptoPunks contract. mint(_punks, CLAIM_AMOUNT * 10000); } /** * @dev renounceOwnership burns the admin key, so this contract is unruggable */ function renounceOwnership() external onlyAdmin { admin = address(0); } /** * @dev setStartingBlock sets the starting block for LP staking rewards * Admin only, used only for initial configuration. * @param _startBlock the block to start rewards for */ function setStartingBlock(uint256 _startBlock) external onlyAdmin { lastRewardBlock = _startBlock; } /** * @dev setPool address to an LP pool. Only Admin. (used only in testing/deployment) */ function setPool(ILiquidityPoolERC20 _addr) external onlyAdmin { require(address(lpToken) == address(0), "pool already set"); lpToken = _addr; } /** * @dev setReward sets the reward. Admin only (used only in testing/deployment) */ function setReward(uint256 _value) public onlyAdmin { cigPerBlock = _value; } /** * @dev buyCEO allows anybody to be the CEO * @param _max_spend the total CIG that can be spent * @param _new_price the new price for the punk (in CIG) * @param _tax_amount how much to pay in advance (in CIG) * @param _punk_index the id of the punk 0-9999 * @param _graffiti a little message / ad from the buyer */ function buyCEO( uint256 _max_spend, uint256 _new_price, uint256 _tax_amount, uint256 _punk_index, bytes32 _graffiti ) external { if (CEO_state == 1 && (taxBurnBlock != block.number)) { _burnTax(); // _burnTax can change CEO_state to 2 } if (CEO_state == 2) { // Auction state. The price goes down 10% every `CEO_auction_blocks` blocks CEO_price = _calcDiscount(); } require (CEO_price + _tax_amount <= _max_spend, "overpaid"); // prevent CEO over-payment require (_new_price >= MIN_PRICE, "price 2 smol"); // price cannot be under 0.000001 CIG require (_punk_index <= 9999, "invalid punk"); // validate the punk index require (_tax_amount >= _new_price / 1000, "insufficient tax" ); // at least %0.1 fee paid for 1 epoch transfer(address(this), CEO_price); // pay for the CEO title burn(address(this), CEO_price); // burn the revenue emit RevenueBurned(msg.sender, CEO_price); _returnDeposit(The_CEO, CEO_tax_balance); // return deposited tax back to old CEO transfer(address(this), _tax_amount); // deposit tax (reverts if not enough) CEO_tax_balance = _tax_amount; // store the tax deposit amount _transferNFT(The_CEO, msg.sender); // yank the NFT to the new CEO CEO_price = _new_price; // set the new price CEO_punk_index = _punk_index; // store the punk id The_CEO = msg.sender; // store the CEO's address taxBurnBlock = block.number; // store the block number // (tax may not have been burned if the // previous state was 0) CEO_state = 1; graffiti = _graffiti; emit TaxDeposit(msg.sender, _tax_amount); emit NewCEO(msg.sender, _punk_index, _new_price, _graffiti); } /** * @dev _returnDeposit returns the tax deposit back to the CEO * @param _to address The address which you want to transfer to * remember to update CEO_tax_balance after calling this */ function _returnDeposit( address _to, uint256 _amount ) internal { if (_amount == 0) { return; } balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; emit Transfer(address(this), _to, _amount); //CEO_tax_balance = 0; // can be omitted since value gets overwritten by caller } /** * @dev transfer the NFT to a new wallet */ function _transferNFT(address _oldCEO, address _newCEO) internal { if (_oldCEO != _newCEO) { The_NFT.transferFrom(_oldCEO, _newCEO, 0); } } /** * @dev depositTax pre-pays tax for the existing CEO. * It may also burn any tax debt the CEO may have. * @param _amount amount of tax to pre-pay */ function depositTax(uint256 _amount) external onlyCEO { require (CEO_state == 1, "no CEO"); if (_amount > 0) { transfer(address(this), _amount); // place the tax on deposit CEO_tax_balance = CEO_tax_balance + _amount; // record the balance emit TaxDeposit(msg.sender, _amount); } if (taxBurnBlock != block.number) { _burnTax(); // settle any tax debt taxBurnBlock = block.number; } } /** * @dev burnTax is called to burn tax. * It removes the CEO if tax is unpaid. * 1. deduct tax, update last update * 2. if not enough tax, remove & begin auction * 3. reward the caller by minting a reward from the amount indebted * A Dutch auction begins where the price decreases 10% every hour. */ function burnTax() external { if (taxBurnBlock == block.number) return; if (CEO_state == 1) { _burnTax(); taxBurnBlock = block.number; } } /** * @dev _burnTax burns any tax debt. Boots the CEO if defaulted, paying a reward to the caller */ function _burnTax() internal { // calculate tax per block (tpb) uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt? CEO_tax_balance = CEO_tax_balance - debt; // deduct tax burn(address(this), debt); // burn the tax emit TaxBurned(msg.sender, debt); } else { // CEO defaulted uint256 default_amount = debt - CEO_tax_balance; // calculate how much defaulted burn(address(this), CEO_tax_balance); // burn the tax emit TaxBurned(msg.sender, CEO_tax_balance); CEO_state = 2; // initiate a Dutch auction. CEO_tax_balance = 0; _transferNFT(The_CEO, address(this)); // This contract holds the NFT temporarily The_CEO = address(this); // This contract is the "interim CEO" mint(msg.sender, default_amount); // reward the caller for reporting tax default emit CEODefaulted(msg.sender, default_amount); } } /** * @dev setPrice changes the price for the CEO title. * @param _price the price to be paid. The new price most be larger tan MIN_PRICE and not default on debt */ function setPrice(uint256 _price) external onlyCEO { require(CEO_state == 1, "No CEO in charge"); require (_price >= MIN_PRICE, "price 2 smol"); require (CEO_tax_balance >= _price / 1000, "price would default"); // need at least 0.1% for tax if (block.number != taxBurnBlock) { _burnTax(); taxBurnBlock = block.number; } // The state is 1 if the CEO hasn't defaulted on tax if (CEO_state == 1) { CEO_price = _price; // set the new price emit CEOPriceChange(_price); } } /** * @dev rewardUp allows the CEO to increase the block rewards by %1 * Can only be called by the CEO every 7 epochs * @return _amount increased by */ function rewardUp() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require (cigPerBlock <= MAX_REWARD, "reward already max"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock + _amount; if (_new_reward > MAX_REWARD) { _amount = MAX_REWARD - cigPerBlock; _new_reward = MAX_REWARD; // cap } cigPerBlock = _new_reward; emit RewardUp(_new_reward, _amount); return _amount; } /** * @dev rewardDown decreases the block rewards by 1% * Can only be called by the CEO every 7 epochs */ function rewardDown() external onlyCEO returns (uint256) { require(CEO_state == 1, "No CEO in charge"); require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks"); require(cigPerBlock >= MIN_REWARD, "reward already low"); rewardsChangedBlock = block.number; uint256 _amount = cigPerBlock / 5; // %20 uint256 _new_reward = cigPerBlock - _amount; if (_new_reward < MIN_REWARD) { _amount = cigPerBlock - MIN_REWARD; _new_reward = MIN_REWARD; } cigPerBlock = _new_reward; emit RewardDown(_new_reward, _amount); return _amount; } /** * @dev _calcDiscount calculates the discount for the CEO title based on how many blocks passed */ function _calcDiscount() internal view returns (uint256) { unchecked { uint256 d = (CEO_price / 10) // 10% discount // multiply by the number of discounts accrued * (block.number - taxBurnBlock) / CEO_auction_blocks; if (d > CEO_price) { // overflow assumed, reset to MIN_PRICE return MIN_PRICE; } uint256 price = CEO_price - d; if (price < MIN_PRICE) { price = MIN_PRICE; } return price; } } /** * @dev getStats helps to fetch some stats for the GUI in a single web3 call * @param _user the address to return the report for * @return uint256[22] the stats * @return address of the current CEO * @return bytes32 Current graffiti */ function getStats(address _user) external view returns(uint256[] memory, address, bytes32, uint112[] memory) { uint[] memory ret = new uint[](22); uint112[] memory reserves = new uint112[](2); uint256 tpb = (CEO_price / 1000) / (CEO_epoch_blocks); // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; uint256 price = CEO_price; UserInfo memory info = userInfo[_user]; if (CEO_state == 2) { price = _calcDiscount(); } ret[0] = CEO_state; ret[1] = CEO_tax_balance; ret[2] = taxBurnBlock; // the block number last tax burn ret[3] = rewardsChangedBlock; // the block of the last staking rewards change ret[4] = price; // price of the CEO title ret[5] = CEO_punk_index; // punk ID of CEO ret[6] = cigPerBlock; // staking reward per block ret[7] = totalSupply; // total supply of CIG if (address(lpToken) != address(0)) { ret[8] = lpToken.balanceOf(address(this)); // Total LP staking ret[16] = lpToken.balanceOf(_user); // not staked by user ret[17] = pendingCig(_user); // pending harvest (reserves[0], reserves[1], ) = lpToken.getReserves(); // uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ret[18] = V2ROUTER.getAmountOut(1 ether, uint(reserves[0]), uint(reserves[1])); // CIG price in ETH if (isContract(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2))) { // are we on mainnet? ILiquidityPoolERC20 ethusd = ILiquidityPoolERC20(address(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f)); // sushi DAI-WETH pool uint112 r0; uint112 r1; (r0, r1, ) = ethusd.getReserves(); // get the price of ETH in USD ret[19] = V2ROUTER.getAmountOut(1 ether, uint(r0), uint(r1)); // ETH price in USD } } ret[9] = block.number; // current block number ret[10] = tpb; // "tax per block" (tpb) ret[11] = debt; // tax debt accrued ret[12] = lastRewardBlock; // the block of the last staking rewards payout update ret[13] = info.deposit; // amount of LP tokens staked by user ret[14] = info.rewardDebt; // amount of rewards paid out ret[15] = balanceOf[_user]; // amount of CIG held by user ret[20] = balanceOf[address(0)]; // amount of CIG burned ret[21] = balanceOf[address(punks)]; // amount of CIG to be claimed return (ret, The_CEO, graffiti, reserves); } /* * ************************ Token distribution and farming stuff **************** */ /** * Claim claims the initial CIG airdrop using a punk * @param _punkIndex the index of the punk, number between 0-9999 */ function claim(uint256 _punkIndex) external returns(bool) { require (_punkIndex <= 9999, "invalid punk"); require(claims[_punkIndex] == false, "punk already claimed"); require(msg.sender == punks.punkIndexToAddress(_punkIndex), "punk 404"); claims[_punkIndex] = true; balanceOf[address(punks)] = balanceOf[address(punks)] - CLAIM_AMOUNT; // deduct from the punks contract balanceOf[msg.sender] = balanceOf[msg.sender] + CLAIM_AMOUNT; // deposit to the caller emit Transfer(address(punks), msg.sender, CLAIM_AMOUNT); emit Claim(msg.sender, _punkIndex, CLAIM_AMOUNT); return true; } /** * @dev update updates the accCigPerShare value and mints new CIG rewards to be distributed to LP stakers * Credits go to MasterChef.sol * Modified the original by removing poolInfo as there is only a single pool * Removed totalAllocPoint and pool.allocPoint * pool.lastRewardBlock moved to lastRewardBlock * There is no need for getMultiplier (rewards are adjusted by the CEO) * */ function update() public { if (block.number <= lastRewardBlock) { return; } uint256 lpSupply = lpToken.balanceOf(address(this)); if (lpSupply == 0) { lastRewardBlock = block.number; return; } // mint some new cigarette rewards to be distributed uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; mint(address(this), cigReward); accCigPerShare = accCigPerShare + ( cigReward * 1e12 / lpSupply ); lastRewardBlock = block.number; } /** * @dev pendingCig displays the amount of cig to be claimed * @param _user the address to report */ function pendingCig(address _user) view public returns (uint256) { uint256 _acps = accCigPerShare; // accumulated cig per share UserInfo storage user = userInfo[_user]; uint256 lpSupply = lpToken.balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock; _acps = _acps + ( cigReward * 1e12 / lpSupply ); } return (user.deposit * _acps / 1e12) - user.rewardDebt; } /** * @dev deposit deposits LP tokens to be staked. It also harvests rewards. * @param _amount the amount of LP tokens to deposit. Assumes this contract has been approved for the _amount. */ function deposit(uint256 _amount) public { UserInfo storage user = userInfo[msg.sender]; update(); if (user.deposit > 0) { uint256 pending = (user.deposit * (accCigPerShare) / 1e12) - user.rewardDebt; safeSendPayout(msg.sender, pending); } if (_amount > 0) { lpToken.transferFrom( address(msg.sender), address(this), _amount ); user.deposit = user.deposit + _amount; emit Deposit(msg.sender, _amount); } user.rewardDebt = user.deposit * accCigPerShare / 1e12; } /** * @dev withdraw takes out the LP tokens and pending rewards * @param _amount the amount to withdraw */ function withdraw(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; require(user.deposit >= _amount, "withdraw: not good"); update(); uint256 pending = (user.deposit * accCigPerShare / 1e12) - user.rewardDebt; safeSendPayout(msg.sender, pending); user.deposit = user.deposit - _amount; user.rewardDebt = user.deposit * accCigPerShare / 1e12; lpToken.transfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _amount); } /** * @dev emergencyWithdraw does a withdraw without caring about rewards. EMERGENCY ONLY. */ function emergencyWithdraw() external { UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.deposit; user.deposit = 0; user.rewardDebt = 0; lpToken.transfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, amount); } /** * @dev safeSendPayout, just in case if rounding error causes pool to not have enough CIGs. * @param _to recipient address * @param _amount the value to send */ function safeSendPayout(address _to, uint256 _amount) internal { uint256 cigBal = balanceOf[address(this)]; if (_amount > cigBal) { _amount = cigBal; } balanceOf[address(this)] = balanceOf[address(this)] - _amount; balanceOf[_to] = balanceOf[_to] + _amount; emit Transfer(address(this), _to, _amount); } /* * ************************ ERC20 Token stuff ******************************** */ /** * @dev burn some tokens * @param _from The address to burn from * @param _amount The amount to burn */ function burn(address _from, uint256 _amount) internal { balanceOf[_from] = balanceOf[_from] - _amount; totalSupply = totalSupply - _amount; emit Transfer(_from, address(0), _amount); } /** * @dev mint new tokens * @param _to The address to mint to. * @param _amount The amount to be minted. */ function mint(address _to, uint256 _amount) internal { require(_to != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply + _amount; balanceOf[_to] = balanceOf[_to] + _amount; emit Transfer(address(0), _to, _amount); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { // require(_value <= balanceOf[msg.sender], "value exceeds balance"); // SafeMath already checks this balanceOf[msg.sender] = balanceOf[msg.sender] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { //require(_value <= balanceOf[_from], "value exceeds balance"); // SafeMath already checks this require(_value <= allowance[_from][msg.sender], "not approved"); balanceOf[_from] = balanceOf[_from] - _value; balanceOf[_to] = balanceOf[_to] + _value; emit Transfer(_from, _to, _value); return true; } /** * @dev Approve tokens of mount _value to be spent by _spender * @param _spender address The spender * @param _value the stipend to spend */ function approve(address _spender, uint256 _value) public returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /******************************************************************** * @dev onSushiReward IRewarder methods to be called by the SushSwap MasterChefV2 contract */ function onSushiReward ( uint256 /* pid */, address _user, address _to, uint256 /* sushiAmount*/, uint256 _newLpAmount) external onlyMCV2 { UserInfo storage user = userInfo[_user]; update(); if (user.deposit > 0) { uint256 pending = (user.deposit * accCigPerShare / 1e12) - user.rewardDebt; safeSendPayout(_to, pending); } user.deposit = _newLpAmount; user.rewardDebt = user.deposit * accCigPerShare / 1e12; } /** * pendingTokens returns the number of pending CIG rewards, implementing IRewarder * @param user it is the only parameter we look at */ function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory) { IERC20[] memory _rewardTokens = new IERC20[](1); _rewardTokens[0] = IERC20(address(this)); uint256[] memory _rewardAmounts = new uint256[](1); _rewardAmounts[0] = pendingCig(user); return (_rewardTokens, _rewardAmounts); } // onlyMCV2 ensures only the MasterChefV2 contract can call this modifier onlyMCV2 { require( msg.sender == MASTERCHEF_V2, "Only MCV2" ); _; } /** * @dev Returns true if `account` is a contract. * * credits https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } /** * @dev sushi router 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F */ interface IRouterV2 { function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns(uint256 amountOut); } interface ICryptoPunk { //function balanceOf(address account) external view returns (uint256); function punkIndexToAddress(uint256 punkIndex) external returns (address); //function punksOfferedForSale(uint256 punkIndex) external returns (bool, uint256, address, uint256, address); //function buyPunk(uint punkIndex) external payable; //function transferPunk(address to, uint punkIndex) external; } interface ICEOERC721 { function transferFrom(address _from, address _to, uint256 _tokenId) external payable; } // IRewarder allows the contract to be called by SushSwap MasterChefV2 // example impl https://etherscan.io/address/0x7519c93fc5073e15d89131fd38118d73a72370f8/advanced#code interface IRewarder { function onSushiReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external; function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory); } /* * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 is IRewarder { /** * @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 * 0xTycoon was here * 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 from UniswapV2Pair.sol */ interface ILiquidityPoolERC20 is IERC20 { function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); }
amount of LP tokens staked by user
ret[13] = info.deposit;
2,101,551
[ 1, 8949, 434, 511, 52, 2430, 384, 9477, 635, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 325, 63, 3437, 65, 273, 1123, 18, 323, 1724, 31, 5397, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.20; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { address public saleAgent; address public partner; modifier onlyAdmin() { require(msg.sender == owner || msg.sender == saleAgent || msg.sender == partner); _; } function setSaleAgent(address newSaleAgent) onlyOwner public { require(newSaleAgent != address(0)); saleAgent = newSaleAgent; } function setPartner(address newPartner) onlyOwner public { require(newPartner != address(0)); partner = newPartner; } event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Pausable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 public storageTime = 1522749600; // 04/03/2018 @ 10:00am (UTC) modifier checkStorageTime() { require(now >= storageTime); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } function setStorageTime(uint256 _time) public onlyOwner { storageTime = _time; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public onlyPayloadSize(2) whenNotPaused checkStorageTime returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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) public onlyPayloadSize(3) whenNotPaused checkStorageTime returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev 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 onlyPayloadSize(2) whenNotPaused 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 available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public onlyPayloadSize(2) returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2) returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken{ event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will recieve 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) public onlyAdmin whenNotPaused canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(this), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is MintableToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyPayloadSize(1) { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } function burnFrom(address _from, uint256 _value) public onlyPayloadSize(2) returns (bool success) { require(balances[_from] >= _value);// Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]);// Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); Burn(_from, _value); return true; } } contract AlttexToken is BurnableToken { string public constant name = "Alttex"; string public constant symbol = "ALTX"; uint8 public constant decimals = 8; }
04/03/2018 @ 10:00am (UTC)
uint256 public storageTime = 1522749600;
331,677
[ 1, 3028, 19, 4630, 19, 21849, 632, 1728, 30, 713, 301, 261, 11471, 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, 225, 2254, 5034, 1071, 2502, 950, 273, 4711, 3787, 5608, 10525, 713, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.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 getLevelByIndex(uint index) public view returns (uint256 price, uint256 available) { price = levels[index].price; available = levels[index].available; }
1,430,047
[ 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, 17236, 21268, 12, 11890, 770, 13, 1071, 1476, 1135, 261, 11890, 5034, 6205, 16, 2254, 5034, 2319, 13, 288, 203, 565, 6205, 273, 7575, 63, 1615, 8009, 8694, 31, 203, 565, 2319, 273, 7575, 63, 1615, 8009, 5699, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x007FEA2a31644F20b0fE18f69643890b6F878AA6/sources/src/bases/BondBaseSDA.sol
@inheritdoc IBondAuctioneer
function getTeller() external view override returns (IBondTeller) { return _teller; }
8,303,963
[ 1, 36, 10093, 16178, 37, 4062, 4943, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3181, 292, 749, 1435, 3903, 1476, 3849, 1135, 261, 45, 9807, 56, 292, 749, 13, 288, 203, 3639, 327, 389, 19261, 749, 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 ]
// 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: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.7; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IAccessControl.sol"; /** * @dev This contract is fully forked from OpenZeppelin `AccessControl`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == _msgSender(), "71"); _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 { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "../interfaces/external/compound/CErc20I.sol"; import "../interfaces/external/compound/IComptroller.sol"; import "../interfaces/external/compound/InterestRateModel.sol"; import "../interfaces/external/uniswap/IUniswapRouter.sol"; import "./GenericLenderBase.sol"; /// @title GenericCompound /// @author Forker from here: https://github.com/Grandthrax/yearnV2-generic-lender-strat/blob/master/contracts/GenericLender/GenericCompound.sol /// @notice A contract to lend any ERC20 to Compound contract GenericCompound is GenericLenderBase { using SafeERC20 for IERC20; using Address for address; event PathUpdated(bytes _path); uint256 public constant BLOCKS_PER_YEAR = 2_350_000; // ==================== References to contracts ============================= CErc20I public immutable cToken; address public immutable comp; IComptroller public immutable comptroller; IUniswapV3Router public immutable uniswapV3Router; // Used to get the `want` price of the AAVE token IUniswapV2Router public immutable uniswapV2Router; address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // ==================== Parameters ============================= bytes public path; uint256 public minCompToSell = 0.5 ether; // ============================= Constructor ============================= /// @notice Constructor of the `GenericCompound` /// @param _strategy Reference to the strategy using this lender /// @param _path Bytes to encode the swap from `comp` to `want` /// @param _cToken Address of the cToken /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _strategy, string memory name, IUniswapV3Router _uniswapV3Router, IUniswapV2Router _uniswapV2Router, IComptroller _comptroller, address _comp, bytes memory _path, address _cToken, address[] memory governorList, address guardian ) GenericLenderBase(_strategy, name, governorList, guardian) { // This transaction is going to revert if `_strategy`, `_comp` or `_cToken` are equal to the zero address require( address(_uniswapV2Router) != address(0) && address(_uniswapV3Router) != address(0) && address(_comptroller) != address(0), "0" ); path = _path; uniswapV3Router = _uniswapV3Router; uniswapV2Router = _uniswapV2Router; comptroller = _comptroller; comp = _comp; cToken = CErc20I(_cToken); require(CErc20I(_cToken).underlying() == address(want), "wrong cToken"); want.safeApprove(_cToken, type(uint256).max); IERC20(_comp).safeApprove(address(_uniswapV3Router), type(uint256).max); } // ===================== External Strategy Functions =========================== /// @notice Deposits the current balance of the contract to the lending platform function deposit() external override onlyRole(STRATEGY_ROLE) { uint256 balance = want.balanceOf(address(this)); require(cToken.mint(balance) == 0, "mint fail"); } /// @notice Withdraws a given amount from lender /// @param amount The amount the caller wants to withdraw /// @return Amount actually withdrawn function withdraw(uint256 amount) external override onlyRole(STRATEGY_ROLE) returns (uint256) { return _withdraw(amount); } /// @notice Withdraws as much as possible from the lending platform /// @return Whether everything was withdrawn or not function withdrawAll() external override onlyRole(STRATEGY_ROLE) returns (bool) { uint256 invested = _nav(); uint256 returned = _withdraw(invested); return returned >= invested; } // ============================= External View Functions ============================= /// @notice Helper function to get the current total of assets managed by the lender. function nav() external view override returns (uint256) { return _nav(); } /// @notice Helper function the current balance of cTokens function underlyingBalanceStored() public view returns (uint256 balance) { uint256 currentCr = cToken.balanceOf(address(this)); if (currentCr == 0) { balance = 0; } else { //The current exchange rate as an unsigned integer, scaled by 1e18. balance = (currentCr * cToken.exchangeRateStored()) / 1e18; } } /// @notice Returns an estimation of the current Annual Percentage Rate function apr() external view override returns (uint256) { return _apr(); } /// @notice Returns an estimation of the current Annual Percentage Rate weighted by a factor function weightedApr() external view override returns (uint256) { uint256 a = _apr(); return a * _nav(); } /// @notice Returns an estimation of the current Annual Percentage Rate after a new deposit /// of `amount` /// @param amount Amount to add to the lending platform, and that we want to take into account /// in the apr computation function aprAfterDeposit(uint256 amount) external view override returns (uint256) { uint256 cashPrior = want.balanceOf(address(cToken)); uint256 borrows = cToken.totalBorrows(); uint256 reserves = cToken.totalReserves(); uint256 reserverFactor = cToken.reserveFactorMantissa(); InterestRateModel model = cToken.interestRateModel(); // The supply rate is derived from the borrow rate, reserve factor and the amount of total borrows. uint256 supplyRate = model.getSupplyRate(cashPrior + amount, borrows, reserves, reserverFactor); // Adding the yield from comp return supplyRate * BLOCKS_PER_YEAR + _incentivesRate(amount); } /// @notice Check if assets are currently managed by this contract function hasAssets() external view override returns (bool) { return cToken.balanceOf(address(this)) > 0 || want.balanceOf(address(this)) > 0; } // ============================= Governance ============================= /// @notice Sets the path for the swap of `comp` tokens /// @param _path New path function setPath(bytes memory _path) external onlyRole(GUARDIAN_ROLE) { path = _path; emit PathUpdated(_path); } /// @notice Withdraws as much as possible in case of emergency and sends it to the `PoolManager` /// @param amount Amount to withdraw /// @dev Does not check if any error occurs or if the amount withdrawn is correct function emergencyWithdraw(uint256 amount) external override onlyRole(GUARDIAN_ROLE) { // Do not care about errors here, what is important is to withdraw what is possible cToken.redeemUnderlying(amount); want.safeTransfer(address(poolManager), want.balanceOf(address(this))); } // ============================= Internal Functions ============================= /// @notice See `apr` function _apr() internal view returns (uint256) { return cToken.supplyRatePerBlock() * BLOCKS_PER_YEAR + _incentivesRate(0); } /// @notice See `nav` function _nav() internal view returns (uint256) { return want.balanceOf(address(this)) + underlyingBalanceStored(); } /// @notice See `withdraw` function _withdraw(uint256 amount) internal returns (uint256) { uint256 balanceUnderlying = cToken.balanceOfUnderlying(address(this)); uint256 looseBalance = want.balanceOf(address(this)); uint256 total = balanceUnderlying + looseBalance; if (amount > total) { // Can't withdraw more than we own amount = total; } if (looseBalance >= amount) { want.safeTransfer(address(strategy), amount); return amount; } // Not state changing but OK because of previous call uint256 liquidity = want.balanceOf(address(cToken)); if (liquidity > 1) { uint256 toWithdraw = amount - looseBalance; if (toWithdraw <= liquidity) { // We can take all require(cToken.redeemUnderlying(toWithdraw) == 0, "redeemUnderlying fail"); } else { // Take all we can require(cToken.redeemUnderlying(liquidity) == 0, "redeemUnderlying fail"); } } _disposeOfComp(); looseBalance = want.balanceOf(address(this)); want.safeTransfer(address(strategy), looseBalance); return looseBalance; } /// @notice Claims and swaps from Uniswap the `comp` earned function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { uniswapV3Router.exactInput(ExactInputParams(path, address(this), block.timestamp, _comp, uint256(0))); } } /// @notice Calculates APR from Compound's Liquidity Mining Program /// @param amountToAdd Amount to add to the `totalSupplyInWant` (for the `aprAfterDeposit` function) function _incentivesRate(uint256 amountToAdd) internal view returns (uint256) { uint256 supplySpeed = comptroller.compSupplySpeeds(address(cToken)); uint256 totalSupplyInWant = (cToken.totalSupply() * cToken.exchangeRateStored()) / 1e18 + amountToAdd; // `supplySpeed` is in `COMP` unit -> the following operation is going to put it in `want` unit supplySpeed = _comptoWant(supplySpeed); uint256 incentivesRate; // Added for testing purposes and to handle the edge case where there is nothing left in a market if (totalSupplyInWant == 0) { incentivesRate = supplySpeed * BLOCKS_PER_YEAR; } else { // `incentivesRate` is expressed in base 18 like all APR incentivesRate = (supplySpeed * BLOCKS_PER_YEAR * 1e18) / totalSupplyInWant; } return (incentivesRate * 9500) / 10000; // 95% of estimated APR to avoid overestimations } /// @notice Estimates the value of `_amount` AAVE tokens /// @param _amount Amount of comp to compute the `want` price of /// @dev This function uses a UniswapV2 oracle to easily compute the price (which is not feasible /// with UniswapV3) function _comptoWant(uint256 _amount) internal view returns (uint256) { if (_amount == 0) { return 0; } // We use a different path when trying to get the price of the AAVE in `want` address[] memory pathPrice; if (address(want) == address(WETH)) { pathPrice = new address[](2); pathPrice[0] = address(comp); pathPrice[1] = address(want); } else { pathPrice = new address[](3); pathPrice[0] = address(comp); pathPrice[1] = address(WETH); pathPrice[2] = address(want); } uint256[] memory amounts = uniswapV2Router.getAmountsOut(_amount, pathPrice); // APRs are in 1e18 return amounts[amounts.length - 1]; } /// @notice Specifies the token managed by this contract during normal operation function _protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](3); protected[0] = address(want); protected[1] = address(cToken); protected[2] = comp; return protected; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../external/AccessControl.sol"; import "../interfaces/IGenericLender.sol"; import "../interfaces/IPoolManager.sol"; import "../interfaces/IStrategy.sol"; /// @title GenericLenderBase /// @author Forked from https://github.com/Grandthrax/yearnV2-generic-lender-strat/tree/master/contracts/GenericLender /// @notice A base contract to build contracts to lend assets abstract contract GenericLenderBase is IGenericLender, AccessControl { using SafeERC20 for IERC20; bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE"); string public override lenderName; // ============================= References to contracts ============================= /// @notice Reference to the protocol's collateral poolManager IPoolManager public poolManager; /// @notice Reference to the `Strategy` address public override strategy; /// @notice Reference to the token lent IERC20 public want; // ============================= Constructor ============================= /// @notice Constructor of the `GenericLenderBase` /// @param _strategy Reference to the strategy using this lender /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _strategy, string memory _name, address[] memory governorList, address guardian ) { strategy = _strategy; // The corresponding `PoolManager` is inferred from the `Strategy` poolManager = IPoolManager(IStrategy(strategy).poolManager()); want = IERC20(poolManager.token()); lenderName = _name; _setupRole(GUARDIAN_ROLE, address(poolManager)); for (uint256 i = 0; i < governorList.length; i++) { _setupRole(GUARDIAN_ROLE, governorList[i]); } _setupRole(GUARDIAN_ROLE, guardian); _setupRole(STRATEGY_ROLE, _strategy); _setRoleAdmin(GUARDIAN_ROLE, STRATEGY_ROLE); _setRoleAdmin(STRATEGY_ROLE, GUARDIAN_ROLE); want.safeApprove(_strategy, type(uint256).max); } // ============================= Governance ============================= /// @notice Override this to add all tokens/tokenized positions this contract /// manages on a *persistent* basis (e.g. not just for swapping back to /// want ephemerally). /// /// Example: /// ``` /// function _protectedTokens() internal override view returns (address[] memory) { /// address[] memory protected = new address[](3); /// protected[0] = tokenA; /// protected[1] = tokenB; /// protected[2] = tokenC; /// return protected; /// } /// ``` function _protectedTokens() internal view virtual returns (address[] memory); /// @notice /// Removes tokens from this Strategy that are not the type of tokens /// managed by this Strategy. This may be used in case of accidentally /// sending the wrong kind of token to this Strategy. /// /// Tokens will be sent to `governance()`. /// /// This will fail if an attempt is made to sweep `want`, or any tokens /// that are protected by this Strategy. /// /// This may only be called by governance. /// @param _token The token to transfer out of this poolManager. /// @param to Address to send the tokens to. /// @dev /// Implement `_protectedTokens()` to specify any additional tokens that /// should be protected from sweeping in addition to `want`. function sweep(address _token, address to) external override onlyRole(GUARDIAN_ROLE) { address[] memory __protectedTokens = _protectedTokens(); for (uint256 i = 0; i < __protectedTokens.length; i++) require(_token != __protectedTokens[i], "93"); IERC20(_token).safeTransfer(to, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IGenericLender /// @author Yearn with slight modifications from Angle Core Team /// @dev Interface for the `GenericLender` contract, the base interface for contracts interacting /// with lending and yield farming platforms interface IGenericLender is IAccessControl { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function sweep(address _token, address to) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IERC721.sol"; import "./IFeeManager.sol"; import "./IOracle.sol"; import "./IAccessControl.sol"; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IFeeManager.sol"; import "./IPerpetualManager.sol"; import "./IOracle.sol"; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IStrategy /// @author Inspired by Yearn with slight changes from Angle Core Team /// @notice Interface for yield farming strategies interface IStrategy is IAccessControl { function estimatedAPR() external view returns (uint256); function poolManager() external view returns (address); function want() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; function withdraw(uint256 _amountNeeded) external returns (uint256 amountFreed, uint256 _loss); function setEmergencyExit() external; function addGuardian(address _guardian) external; function revokeGuardian(address _guardian) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import "./CTokenI.sol"; interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function underlying() external view returns (address); function borrow(uint256 borrowAmount) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./InterestRateModel.sol"; interface CTokenI { function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function supplyRatePerBlock() external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface IComptroller { function compSupplySpeeds(address cToken) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface InterestRateModel { /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); // Rinkeby function function getBorrowRate( uint256 cash, uint256 borrows, uint256 _reserves ) external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3Router { /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); } /// @title Router for price estimation functionality /// @notice Functions for getting the price of one token with respect to another using Uniswap V2 /// @dev This interface is only used for non critical elements of the protocol interface IUniswapV2Router { /// @notice Given an input asset amount, returns the maximum output amount of the /// other asset (accounting for fees) given reserves. /// @param path Addresses of the pools used to get prices function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); }
@notice Sets the path for the swap of `comp` tokens @param _path New path
function setPath(bytes memory _path) external onlyRole(GUARDIAN_ROLE) { path = _path; emit PathUpdated(_path); }
1,475,911
[ 1, 2785, 326, 589, 364, 326, 7720, 434, 1375, 2919, 68, 2430, 225, 389, 803, 1166, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16475, 12, 3890, 3778, 389, 803, 13, 3903, 1338, 2996, 12, 30673, 985, 2565, 1258, 67, 16256, 13, 288, 203, 3639, 589, 273, 389, 803, 31, 203, 3639, 3626, 2666, 7381, 24899, 803, 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 ]
./full_match/84531/0x7D1d608630F311ebBa6bb56AA3Ac4ef8e0F52dD8/sources/contracts/MerkleDistributor.sol
Verify the merkle proof. Mark it claimed and send the token.
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external { require(!isClaimed(account), 'MerkleDistributor: Drop already claimed.'); bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.'); _setClaimed(account); require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.'); emit Claimed(index, account, amount); }
14,318,568
[ 1, 8097, 326, 30235, 14601, 18, 6622, 518, 7516, 329, 471, 1366, 326, 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, 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, 7516, 12, 11890, 5034, 770, 16, 1758, 2236, 16, 2254, 5034, 3844, 16, 1731, 1578, 8526, 745, 892, 30235, 20439, 13, 3903, 288, 203, 3639, 2583, 12, 5, 291, 9762, 329, 12, 4631, 3631, 296, 8478, 15609, 1669, 19293, 30, 10895, 1818, 7516, 329, 1093, 1769, 203, 203, 3639, 1731, 1578, 756, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1615, 16, 2236, 16, 3844, 10019, 203, 3639, 2583, 12, 8478, 15609, 20439, 18, 8705, 12, 6592, 15609, 20439, 16, 30235, 2375, 16, 756, 3631, 296, 8478, 15609, 1669, 19293, 30, 1962, 14601, 1093, 1769, 203, 203, 3639, 389, 542, 9762, 329, 12, 4631, 1769, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 2934, 13866, 12, 4631, 16, 3844, 3631, 296, 8478, 15609, 1669, 19293, 30, 12279, 2535, 1093, 1769, 203, 203, 3639, 3626, 18381, 329, 12, 1615, 16, 2236, 16, 3844, 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 ]
./full_match/4/0x8a527ad47F223b5894a9E8793c3c0c962fE7ac51/sources/contracts/interfaces/IManager.sol
bytes can take on the form of deploying or recovering liquidity
interface IManager { struct ControllerTransferData { } struct PoolTransferData { } struct MaintenanceExecution { ControllerTransferData[] cycleSteps; } struct RolloverExecution { PoolTransferData[] poolData; ControllerTransferData[] cycleSteps; string rewardsIpfsHash; } event ControllerRegistered(bytes32 id, address controller); event ControllerUnregistered(bytes32 id, address controller); event PoolRegistered(address pool); event PoolUnregistered(address pool); event CycleDurationSet(uint256 duration); event LiquidityMovedToManager(address pool, uint256 amount); event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data); event LiquidityMovedToPool(address pool, uint256 amount); event CycleRolloverStarted(uint256 blockNumber); event CycleRolloverComplete(uint256 blockNumber); event DestinationsSet(address destinationOnL1, address destinationOnL2); event EventSendSet(bool eventSendSet); }
13,296,305
[ 1, 3890, 848, 4862, 603, 326, 646, 434, 7286, 310, 578, 5910, 310, 4501, 372, 24237, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 467, 1318, 288, 203, 203, 203, 565, 1958, 6629, 5912, 751, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 5912, 751, 288, 203, 565, 289, 203, 203, 565, 1958, 27532, 3210, 288, 203, 540, 6629, 5912, 751, 8526, 8589, 11811, 31, 203, 565, 289, 203, 203, 565, 1958, 11714, 21896, 3210, 288, 203, 3639, 8828, 5912, 751, 8526, 2845, 751, 31, 203, 3639, 6629, 5912, 751, 8526, 8589, 11811, 31, 203, 3639, 533, 283, 6397, 5273, 2556, 2310, 31, 203, 565, 289, 203, 203, 565, 871, 6629, 10868, 12, 3890, 1578, 612, 16, 1758, 2596, 1769, 203, 565, 871, 6629, 984, 14327, 12, 3890, 1578, 612, 16, 1758, 2596, 1769, 203, 565, 871, 8828, 10868, 12, 2867, 2845, 1769, 203, 565, 871, 8828, 984, 14327, 12, 2867, 2845, 1769, 203, 565, 871, 385, 3409, 5326, 694, 12, 11890, 5034, 3734, 1769, 203, 565, 871, 511, 18988, 24237, 25317, 774, 1318, 12, 2867, 2845, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 8587, 4160, 23839, 12, 3890, 1578, 2596, 16, 1758, 1261, 438, 2045, 1887, 16, 1731, 501, 1769, 203, 565, 871, 511, 18988, 24237, 25317, 774, 2864, 12, 2867, 2845, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 385, 3409, 4984, 21896, 9217, 12, 11890, 5034, 1203, 1854, 1769, 203, 565, 871, 385, 3409, 4984, 21896, 6322, 12, 11890, 5034, 1203, 1854, 1769, 203, 565, 871, 28510, 10144, 694, 12, 2867, 2929, 1398, 48, 21, 16, 1758, 2929, 1398, 48, 22, 1769, 203, 565, 871, 2587, 3826, 694, 12, 6430, 871, 3826, 2 ]
./partial_match/1/0x6Bd395902b2D18Bc955d1a41C6b7ddF7b301930A/sources/contracts/XOLE.sol
Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block First check most recent balance Next check implicit zero balance ceil, avoiding overflow
function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "getPriorVotes:not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
2,745,494
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 8416, 16, 4543, 310, 9391, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 588, 25355, 29637, 30, 902, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 2254, 1578, 4617, 273, 3854, 300, 261, 5797, 300, 2612, 13, 342, 576, 31, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2 ]